C Programming Examples: Essential Algorithms

This document provides a collection of fundamental C programming examples, demonstrating common algorithms and data structure manipulations. Each section presents a self-contained C code snippet that you can compile and run to understand core programming concepts.

Prime Number Check

This C program determines if a given integer is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

#include <stdio.h>

int main() {
    int num, i, isPrime = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num <= 1) {
        isPrime = 0;
    } else {
        for (i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if (isPrime)
        printf("%d is a prime number.\n", num);
    else
        printf("%d is not a prime number.\n", num);

    return 0;
}

Factorial Calculation

This program calculates the factorial of a non-negative integer. The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

#include <stdio.h>

int main() {
    int num, i;
    unsigned long long factorial = 1;

    printf("Enter a non-negative integer: ");
    scanf("%d", &num);

    // Factorial of negative numbers doesn't exist
    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        for (i = 1; i <= num; ++i) {
            factorial *= i;
        }
        printf("Factorial of %d = %llu\n", num, factorial);
    }

    return 0;
}

Armstrong Number Check

An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or plus perfect number) is a number that is the sum of its own digits each raised to the power of the number of digits.

#include <stdio.h>
#include <math.h> // Required for pow() function

int main() {
    int num, originalNum, remainder, result = 0, n = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    originalNum = num;

    // Count the number of digits
    while (originalNum != 0) {
        originalNum /= 10;
        n++;
    }

    originalNum = num;

    // Calculate the sum of powers of digits
    while (originalNum != 0) {
        remainder = originalNum % 10;
        result += pow(remainder, n);
        originalNum /= 10;
    }

    if (result == num)
        printf("%d is an Armstrong number.\n", num);
    else
        printf("%d is not an Armstrong number.\n", num);

    return 0;
}

Greatest Common Divisor (GCD) Calculation

This program calculates the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm. The GCD is the largest positive integer that divides both numbers without leaving a remainder.

#include <stdio.h>

int main() {
    int a, b, gcd;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    // Euclidean algorithm
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }

    gcd = a;

    printf("GCD is %d\n", gcd);

    return 0;
}

Matrix Multiplication

This C program performs matrix multiplication for two predefined matrices. It includes checks to ensure that multiplication is possible based on matrix dimensions.

#include <stdio.h>
#include <stdlib.h>

#define R1 2 // Number of rows in matrix 1
#define C1 2 // Number of columns in matrix 1
#define R2 2 // Number of rows in matrix 2
#define C2 3 // Number of columns in matrix 2

// Function to multiply two matrices
void multiplyMatrix(int m1[][C1], int m2[][C2]) {
    int result[R1][C2];
    printf("Resultant Matrix:\n");
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < R2; k++)
                result[i][j] += m1[i][k] * m2[k][j];
            printf("%d\t", result[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int m1[R1][C1] = {{1, 1}, {2, 2}};
    int m2[R2][C2] = {{1, 1, 1}, {2, 2, 2}};

    // Check if matrix multiplication is possible
    if (C1 != R2) {
        printf("Matrix multiplication not possible. Update dimensions.\n");
        exit(EXIT_FAILURE);
    }

    multiplyMatrix(m1, m2);

    return 0;
}

Sort Elements in Ascending Order

This program sorts an array of integers in ascending order using the Bubble Sort algorithm. It dynamically allocates memory for the array.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, i, j, temp;
    printf("Enter number of elements: ");
    if (scanf("%d", &n) != 1 || n <= 0) {
        printf("Invalid size. Please enter a positive integer.\n");
        return EXIT_FAILURE;
    }

    int *arr = malloc(n * sizeof *arr);
    if (!arr) {
        printf("Memory allocation failed.\n");
        return EXIT_FAILURE;
    }

    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) {
            printf("Invalid input. Please enter an integer.\n");
            free(arr);
            return EXIT_FAILURE;
        }
    }

    // Sort array in ascending order (Bubble Sort)
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            if (arr[i] > arr[j]) {
                temp    = arr[i];
                arr[i]  = arr[j];
                arr[j]  = temp;
            }
        }
    }

    printf("Sorted array: ");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);
    return 0;
}

Searching an Element in an Array

This program searches for a specific element within an array and reports its position if found. It uses a linear search approach.

#include <stdio.h>

int main() {
    int arr[100], n, i, key, found = 0;

    printf("Enter number of elements (max 100): ");
    scanf("%d", &n);

    if (n <= 0 || n > 100) {
        printf("Invalid number of elements. Please enter a value between 1 and 100.\n");
        return 1;
    }

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    printf("Enter the element to search: ");
    scanf("%d", &key);

    for (i = 0; i < n; i++) {
        if (arr[i] == key) {
            found = 1;
            break;
        }
    }

    if (found)
        printf("%d found at position %d.\n", key, i + 1); // 1-based index
    else
        printf("%d not found in the array.\n", key);

    return 0;
}

Leap Year Check

This C program determines whether a given year is a leap year or not, based on the standard leap year rules.

#include <stdio.h>

int main() {
    int year;
    printf("Enter a year: ");
    scanf("%d", &year);

    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
        printf("%d is a leap year.\n", year);
    else
        printf("%d is not a leap year.\n", year);

    return 0;
}

Degrees Fahrenheit to Celsius Conversion

This program converts a temperature value from Fahrenheit to Celsius using the standard conversion formula.

#include <stdio.h>

int main() {
    float fahrenheit, celsius;

    printf("Enter temperature in Fahrenheit: ");
    scanf("%f", &fahrenheit);

    celsius = (fahrenheit - 32) * 5 / 9;

    printf("%.2f Fahrenheit = %.2f Celsius\n", fahrenheit, celsius);

    return 0;
}

Array Minimum and Maximum Elements

This program finds the minimum and maximum elements within an array of integers. It first prompts the user for the array size and then the elements.

#include <stdio.h>

int main() {
    int n, i, min, max;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    if (n <= 0) {
        printf("Invalid number of elements. Please enter a positive integer.\n");
        return 1;
    }

    // Using VLA (Variable Length Array) - C99 feature
    int arr[n];
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    min = max = arr[0]; // Initialize min and max with first element

    for (i = 1; i < n; i++) {
        if (arr[i] < min)
            min = arr[i];
        if (arr[i] > max)
            max = arr[i];
    }

    printf("Minimum element = %d\n", min);
    printf("Maximum element = %d\n", max);

    return 0;
}

These examples cover a range of basic C programming tasks, providing a solid foundation for understanding more complex algorithms and data structures.