Top 30 Trending C Coding Examples

To understand these Python examples, you should know the following:

1. Write a C program to reverse a string in place without using additional string memory

Code:

#include <stdio.h>
#include <string.h>

void reverseString(char *str) {
    int left = 0;
    int right = strlen(str) - 1;
    while (left < right) {
        char temp = str[left];
        str[left] = str[right];
        str[right] = temp;
        left++;
        right--;
    }
}

int main() {
    char str[] = "C Programming";
    reverseString(str);
    printf("%s\n", str);
    return 0;
}

Output:

gnimmargorP C

Explanation: Uses a two-pointer approach swapping characters from opposite ends moving toward the middle until they meet.

2. Write a C function to check if a string reads the same backward as forward.

Code:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isPalindrome(const char *str) {
    int left = 0;
    int right = strlen(str) - 1;
    while (left < right) {
        if (str[left] != str[right]) return false;
        left++;
        right--;
    }
    return true;
}

int main() {
    printf("%s\n", isPalindrome("madam") ? "True" : "False");
    return 0;
}

Output:

True

Explanation: Compares characters starting from the outer boundary moving inward. If any mismatched characters are encountered, returns false.

3. Swap the values of two variables without using a temporary variable in C Programming

Code:

#include <stdio.h>

int main() {
    int a = 10, b = 20;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("a = %d, b = %d\n", a, b);
    return 0;
}

Output:

a = 20, b = 10

Explanation: Uses arithmetic addition and subtraction to reassign values to a and b without allocating additional temporary memory.

4. Find the minimum and maximum values in an array of integers with C Programming

Code:

#include <stdio.h>

int main() {
    int arr[] = {34, 12, 89, 5, 67};
    int size = sizeof(arr) / sizeof(arr[0]);
    int min = arr[0], max = arr[0];

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

    printf("Min: %d, Max: %d\n", min, max);
    return 0;
}

Output:

Min: 5, Max: 89

Explanation: Initializes min and max with the first element, then traverses the array updating boundaries whenever smaller or larger values appear.

5. Dynamically allocate an array of integers using malloc, input values, and free memory in C Programming

Code:

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

int main() {
    int n = 3;
    int *ptr = (int *)malloc(n * sizeof(int));
    
    if (ptr == NULL) return 1;

    for (int i = 0; i < n; i++) ptr[i] = (i + 1) * 10;
    for (int i = 0; i < n; i++) printf("%d ", ptr[i]);

    free(ptr);
    return 0;
}

Output:

10 20 30

Explanation: Allocates memory on the heap dynamically via malloc(). The memory block is explicitly deallocated using free() to prevent leaks.

6. Write a function that checks whether an integer is prime in C Programming

Code:

#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    printf("%d is %s\n", 29, isPrime(29) ? "Prime" : "Not Prime");
    return 0;
}

Output:

29 is Prime

Explanation: Checks divisibility up to square root of n. If no integer divides n without remainder, n is prime.

7. Generate the first n numbers in the Fibonacci sequence without recursion in C Programming

Code:

#include <stdio.h>

void printFibonacci(int n) {
    int a = 0, b = 1, next;
    for (int i = 0; i < n; i++) {
        printf("%d ", a);
        next = a + b;
        a = b;
        b = next;
    }
}

int main() {
    printFibonacci(6);
    return 0;
}

Output:

0 1 1 2 3 5

Explanation: Maintains running values for previous terms a and b, computing the next term iteratively in O(n) time.

8. Compute n-th Fibonacci number recursively in C Programming

Code:

#include <stdio.h>

int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    printf("Fibonacci at index 6: %d\n", fibonacci(6));
    return 0;
}

Output:

Fibonacci at index 6: 8

Explanation: Breaks down computation recursively into F(n) = F(n-1) + F(n-2) until base cases 0 or 1 are hit.

9. Count the total number of vowels and consonants in a string with C Programming

Code:

#include <stdio.h>
#include <ctype.h>

int main() {
    char str[] = "Hello World!";
    int vowels = 0, consonants = 0;

    for (int i = 0; str[i] != '\0'; i++) {
        char ch = tolower(str[i]);
        if (ch >= 'a' && ch <= 'z') {
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                vowels++;
            else
                consonants++;
        }
    }
    printf("Vowels: %d, Consonants: %d\n", vowels, consonants);
    return 0;
}

Output:

Vowels: 3, Consonants: 7

Explanation: Iterates through characters, converting letters to lowercase to count vowels vs remaining alphabetic consonants.

10. Implement Bubble Sort algorithm to sort an integer array in ascending order in C Programming

Code:

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22};
    int n = sizeof(arr) / sizeof(arr[0]);
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    return 0;
}

Output:

12 22 25 34 64

Explanation: Iteratively compares adjacent elements, swapping them if out of order until the largest elements float to the top end.

11. Implement binary search on a sorted array in C Programming

Code:

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {
    int low = 0, high = size - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main() {
    int arr[] = {2, 5, 8, 12, 16, 23, 38};
    int index = binarySearch(arr, 7, 16);
    printf("Found at index: %d\n", index);
    return 0;
}

Output:

Found at index: 4

Explanation: Repeatedly divides the sorted search space in half to locate target value in O(log n) time.

12. Write a function to calculate the factorial of n recursively in C Programming

Code:

#include <stdio.h>

long long factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

int main() {
    printf("Factorial of 5 = %lld\n", factorial(5));
    return 0;
}

Output:

Factorial of 5 = 120

Explanation: Recursively multiplies n by (n-1)! until reaching base condition 1! = 1.

13. Perform multiplication of two 2D matrices in C Programming

Code:

#include <stdio.h>

int main() {
    int A[2][2] = {{1, 2}, {3, 4}};
    int B[2][2] = {{5, 6}, {7, 8}};
    int C[2][2] = {0};

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }

    printf("%d %d\n%d %d\n", C[0][0], C[0][1], C[1][0], C[1][1]);
    return 0;
}

Output:

19 22
43 50

Explanation: Uses triple nested loops calculating dot products between row vectors of matrix A and column vectors of matrix B.

14. Determine if a 3-digit integer is an Armstrong number with C Programming

Code:

#include <stdio.h>

int isArmstrong(int num) {
    int original = num, sum = 0, remainder;
    while (original != 0) {
        remainder = original % 10;
        sum += remainder * remainder * remainder;
        original /= 10;
    }
    return sum == num;
}

int main() {
    printf("%d\n", isArmstrong(153));
    return 0;
}

Output:

1

Explanation: Extracts digits of 153, calculates 1^3 + 5^3 + 3^3 = 153, matching original number.

15. Declare and call a function using a function pointer in C Programming

Code:

#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main() {
    int (*func_ptr)(int, int) = add;
    int result = func_ptr(10, 20);
    printf("Sum: %d\n", result);
    return 0;
}

Output:

Sum: 30

Explanation: Declares a pointer variable func_ptr storing execution address of add(), enabling dynamic function callbacks.

16. Create a singly linked list with nodes, insert at head, and print list in C Programming

Code:

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

struct Node {
    int data;
    struct Node* next;
};

void insertHead(struct Node** head, int val) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = val;
    newNode->next = *head;
    *head = newNode;
}

int main() {
    struct Node* head = NULL;
    insertHead(&head, 30);
    insertHead(&head, 20);
    insertHead(&head, 10);

    struct Node* curr = head;
    while (curr) {
        printf("%d -> ", curr->data);
        curr = curr->next;
    }
    printf("NULL\n");
    return 0;
}

Output:

10 -> 20 -> 30 -> NULL

Explanation: Allocates new structural heap nodes setting data attributes and linking next pointers to point to head.

17. Determine if an integer is odd or even using bitwise & operator in C Programming

Code:

#include <stdio.h>

int main() {
    int n = 7;
    if (n & 1) {
        printf("%d is Odd\n", n);
    } else {
        printf("%d is Even\n", n);
    }
    return 0;
}

Output:

7 is Odd

Explanation: Performs binary bitwise AND with 1. If least significant bit is 1, number is odd; otherwise even.

18. Modify structure attributes by passing structure pointer to a function in C Programming

Code:

#include <stdio.h>

struct Student {
    char name[20];
    int score;
};

void updateScore(struct Student *s, int newScore) {
    s->score = newScore;
}

int main() {
    struct Student st = {"Alex", 80};
    updateScore(&st, 95);
    printf("Name: %s, Score: %d\n", st.name, st.score);
    return 0;
}

Output:

Name: Alex, Score: 95

Explanation: Passes address &st allowing updateScore() to dereference structural values via arrow operator (->).

19. Write text to a file and read it back using file I/O operations with C Programming

Code:

#include <stdio.h>

int main() {
    FILE *fp = fopen("test.txt", "w+");
    if (fp == NULL) return 1;

    fputs("C File IO Test", fp);
    fseek(fp, 0, SEEK_SET);

    char buffer[50];
    fgets(buffer, sizeof(buffer), fp);
    printf("Read: %s\n", buffer);

    fclose(fp);
    return 0;
}

Output:

Read: C File IO Test

Explanation: Opens file descriptor, writes buffer data with fputs, rewinds file pointer using fseek, and reads via fgets.

20. Compute Greatest Common Divisor (GCD) of two numbers recursively in C Programming

Code:

#include <stdio.h>

int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

int main() {
    printf("GCD of 48 and 18: %d\n", gcd(48, 18));
    return 0;
}

Output:

GCD of 48 and 18: 6

Explanation: Applies Euclidean algorithm recursively gcd(b, a % b) until second parameter reaches 0.

21. Create a variadic function taking a variable number of arguments using <stdarg.h> with C Programming

Code:

#include <stdio.h>
#include <stdarg.h>

int sumAll(int count, ...) {
    va_list args;
    va_start(args, count);
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += va_arg(args, int);
    }
    va_end(args);
    return total;
}

int main() {
    printf("Sum: %d\n", sumAll(4, 10, 20, 30, 40));
    return 0;
}

Output:

Sum: 100

Explanation: Uses stdarg.h macros (va_list, va_start, va_arg, va_end) to process arbitrary number of parameters.

22. Implement the Quick Sort divide-and-conquer algorithm with C Programming

Code:

#include <stdio.h>

void swap(int* a, int* b) {
    int t = *a; *a = *b; *b = t;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {10, 7, 8, 9, 1, 5};
    quickSort(arr, 0, 5);
    for (int i = 0; i < 6; i++) printf("%d ", arr[i]);
    return 0;
}

Output:

1 5 7 8 9 10

Explanation: Chooses a pivot, partitions elements into lower/higher segments, and recursively sorts sub-arrays.

23. Remove duplicates from a sorted array in place with C Programming

Code:

#include <stdio.h>

int removeDuplicates(int arr[], int n) {
    if (n == 0 || n == 1) return n;
    int j = 0;
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] != arr[i + 1]) {
            arr[j++] = arr[i];
        }
    }
    arr[j++] = arr[n - 1];
    return j;
}

int main() {
    int arr[] = {1, 1, 2, 2, 3, 4, 4};
    int newSize = removeDuplicates(arr, 7);
    for (int i = 0; i < newSize; i++) printf("%d ", arr[i]);
    return 0;
}

Output:

1 2 3 4

Explanation: Overwrites duplicate entries using secondary write pointer j whenever value changes.

24. Find the second maximum value in an integer array in a single traversal pass with C Programming

Code:

#include <stdio.h>
#include <limits.h>

int secondLargest(int arr[], int size) {
    int first = INT_MIN, second = INT_MIN;
    for (int i = 0; i < size; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] != first) {
            second = arr[i];
        }
    }
    return second;
}

int main() {
    int arr[] = {12, 35, 1, 10, 34, 1};
    printf("Second largest: %d\n", secondLargest(arr, 6));
    return 0;
}

Output:

Second largest: 34

Explanation: Updates first and second dynamically while scanning through array elements once.

25. Count the number of set bits (1s) in binary representation of integer using Brian Kernighan’s Algorithm with C Programming

Code:

#include <stdio.h>

int countSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n &= (n - 1);
        count++;
    }
    return count;
}

int main() {
    printf("Set bits in 13: %d\n", countSetBits(13));
    return 0;
}

Output:

Set bits in 13: 3

Explanation: n & (n – 1) clears least significant set bit repeatedly until n becomes zero. (Binary of 13 is 1101).

26. Create a basic Stack data structure supporting push and pop operations in C Programming

Code:

#include <stdio.h>
#define MAX 5

int stack[MAX];
int top = -1;

void push(int val) {
    if (top < MAX - 1) stack[++top] = val;
}

int pop() {
    if (top >= 0) return stack[top--];
    return -1;
}

int main() {
    push(10);
    push(20);
    printf("Popped: %d\n", pop());
    printf("Popped: %d\n", pop());
    return 0;
}

Output:

Popped: 20
Popped: 10

Explanation: Implements LIFO (Last In First Out) behavior using an array tracker variable top.

27. Implement Queue structure using Array with Enqueue and Dequeue logic in C Programming

Code:

#include <stdio.h>

#define SIZE 5
int items[SIZE], front = -1, rear = -1;

void enqueue(int value) {
    if (rear == SIZE - 1) return;
    if (front == -1) front = 0;
    items[++rear] = value;
}

int dequeue() {
    if (front == -1 || front > rear) return -1;
    return items[front++];
}

int main() {
    enqueue(1);
    enqueue(2);
    printf("Dequeued: %d\n", dequeue());
    printf("Dequeued: %d\n", dequeue());
    return 0;
}

Output:

Dequeued: 1
Dequeued: 2

Explanation: Implements FIFO (First In First Out) processing using dual index tracking pointers front and rear.

28. Allocate and free dynamic 2D array matrix using pointers to pointers (int **) in C Programming

Code:

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

int main() {
    int rows = 2, cols = 3;
    int **arr = (int **)malloc(rows * sizeof(int *));
    for (int i = 0; i < rows; i++) {
        arr[i] = (int *)malloc(cols * sizeof(int));
    }

    arr[1][2] = 42;
    printf("Value at [1][2]: %d\n", arr[1][2]);

    for (int i = 0; i < rows; i++) free(arr[i]);
    free(arr);
    return 0;
}

Output:

Value at [1][2]: 42

Explanation: Allocates an array of row pointers, then allocates integer memory for each individual column row.

29. Given an array containing numbers from 1 to n with one missing element, find the missing value in C Programming

Code:

#include <stdio.h>

int findMissing(int arr[], int n) {
    int total = (n + 1) * (n + 2) / 2;
    for (int i = 0; i < n; i++) {
        total -= arr[i];
    }
    return total;
}

int main() {
    int arr[] = {1, 2, 4, 5, 6};
    printf("Missing: %d\n", findMissing(arr, 5));
    return 0;
}

Output:

Missing: 3

Explanation: Calculates the expected sum of the sequence and subtracts the existing array elements to locate the missing number.

30. Use C enum inside switch statement to handle custom status states

Code:

#include <stdio.h>

enum Status { SUCCESS, WARNING, ERROR };

void handleStatus(enum Status s) {
    switch (s) {
        case SUCCESS: printf("Operation Successful\n"); break;
        case WARNING: printf("Operation Warning\n"); break;
        case ERROR:   printf("Operation Error\n"); break;
    }
}

int main() {
    enum Status currentStatus = SUCCESS;
    handleStatus(currentStatus);
    return 0;
}

Output:

Operation Successful

Explanation: An enum maps custom state representations to constant integer values for readable control flow.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

Write a C program To Add Two Integers
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment