C All Exercises & Assignments

Write a C program to sort an array using bubble sort

Description: Take 5 numbers in an array and sort them in ascending order.

Hint:

  • Compare each pair of neighbours. If the left one is bigger, swap them. Repeat this until the array is sorted.

C program for bubble sort

#include <stdio.h>

int main(void) {
    int a[5], temp;

    printf("Enter 5 numbers: ");
    for (int i = 0; i < 5; i++) {
        scanf("%d", &a[i]);
    }

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4 - i; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

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

Output:

Output of the above program is

Enter 5 numbers: 64
25
12
22
11
Sorted array: 11 12 22 25 64

How it works

  • After the first pass of the outer loop, the biggest number (64) has moved to the end. After the second pass, the second biggest is in its place, and so on.
  • The inner loop runs 4 - i times, because the last i elements are already sorted.

Write a C program to search an element in an array

Description: Take an array of 5 numbers and a number to search. Print its position, or a message if it is not found.

Hint:

  • Compare the number with every element one by one. Stop when it is found.

C program for linear search

#include <stdio.h>

int main(void) {
    int a[5] = {12, 45, 7, 67, 30};
    int key, found = -1;

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

    for (int i = 0; i < 5; i++) {
        if (a[i] == key) {
            found = i;
            break;
        }
    }

    if (found != -1) {
        printf("%d found at index %d\n", key, found);
    } else {
        printf("%d not found\n", key);
    }
    return 0;
}

Output:

Output of the above program is

Enter the number to search: 67
67 found at index 3

How it works

  • found starts as -1, which means “not found”.
  • When the value matches, we save the index in found and stop the loop with break.
  • Index 3 is the fourth element, because indexes start from 0.

Write a C program to add two matrices

Description: Take the elements of two 2 x 2 matrices as input. Print the sum matrix.

Hint:

  • Add the elements which are at the same row and column: sum[i][j] = a[i][j] + b[i][j].

C program to add two matrices

#include <stdio.h>

int main(void) {
    int a[2][2], b[2][2], sum[2][2];

    printf("Enter 4 elements of the first matrix: ");
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            scanf("%d", &a[i][j]);

    printf("Enter 4 elements of the second matrix: ");
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            scanf("%d", &b[i][j]);

    printf("Sum of the matrices:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            sum[i][j] = a[i][j] + b[i][j];
            printf("%d ", sum[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output:

Output of the above program is

Enter 4 elements of the first matrix: 1
2
3
4
Enter 4 elements of the second matrix: 5
6
7
8
Sum of the matrices:
6 8
10 12

How it works

  • The nested loops go through each row and each column.
  • The result matrix has two rows: 6 8 and 10 12.

Read C Two Dimensional Arrays.

Write a C program to find the length of a string without using strlen

Description: Take a word as input. Count its characters without using the strlen() function.

Hint:

  • A string ends with the null character '\0'. Count the characters before it.

C program to find the length of a string

#include <stdio.h>

int main(void) {
    char s[50];
    int length = 0;

    printf("Enter a word: ");
    scanf("%49s", s);

    while (s[length] != '\0') {
        length++;
    }
    printf("Length = %d\n", length);
    return 0;
}

Output:

Output of the above program is

Enter a word: Programming
Length = 11

How it works

  • The loop moves one character at a time, and stops at the null character.
  • The value of length at that point is the number of characters.

Read C Strings and strlen().

Write a C program to reverse a string

Description: Take a word as input and print it in reverse order.

Hint:

  • Use two variables for the first and last index. Swap the characters and move both towards the middle.

C program to reverse a string

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

int main(void) {
    char s[50];

    printf("Enter a word: ");
    scanf("%49s", s);

    int left = 0, right = strlen(s) - 1;
    while (left < right) {
        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;
        left++;
        right--;
    }
    printf("Reversed: %s\n", s);
    return 0;
}

Output:

Output of the above program is

Enter a word: Hello
Reversed: olleH

How it works

  • “Hello” has 5 characters. First ‘H’ and ‘o’ are swapped, then ‘e’ and ‘l’. The middle ‘l’ stays.
  • The loop stops when left is not less than right.

Read Reverse a String in C.

Write a C program to check whether a string is a palindrome

Description: Take a word as input. Print if it is a palindrome, like “madam” or “level”.

Hint:

  • Compare the first character with the last, the second with the second last, and so on.

C program to check a palindrome string

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

int main(void) {
    char s[50];
    int isPalindrome = 1;

    printf("Enter a word: ");
    scanf("%49s", s);

    int n = strlen(s);
    for (int i = 0; i < n / 2; i++) {
        if (s[i] != s[n - 1 - i]) {
            isPalindrome = 0;
            break;
        }
    }

    if (isPalindrome) {
        printf("%s is a palindrome\n", s);
    } else {
        printf("%s is not a palindrome\n", s);
    }
    return 0;
}

Output:

Output of the above program is

Enter a word: level
level is a palindrome

How it works

  • We only need to check half of the string (n / 2 pairs).
  • One mismatch is enough to say it is not a palindrome, so we stop with break.

Write a C program to count the vowels in a string

Description: Take a word as input. Print how many vowels (a, e, i, o, u) it has.

Hint:

  • Go through each character. Convert it to lower case, and check if it is one of the five vowels.

C program to count the vowels

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

int main(void) {
    char s[50];
    int count = 0;

    printf("Enter a word: ");
    scanf("%49s", s);

    for (int i = 0; s[i] != '\0'; i++) {
        switch (tolower((unsigned char)s[i])) {
            case 'a': case 'e': case 'i': case 'o': case 'u':
                count++;
        }
    }
    printf("Vowels = %d\n", count);
    return 0;
}

Output:

Output of the above program is

Enter a word: Education
Vowels = 5

How it works

  • “Education” has the vowels E, u, a, i, o, so the answer is 5.
  • tolower() makes the check work for capital letters also.

Write a C program to find the factorial of a number using recursion

Description: Write a recursive function to find the factorial of a number taken as input.

Hint:

  • n! = n x (n - 1)! and 0! = 1. The second rule is the base case.

C program for factorial using recursion

#include <stdio.h>

unsigned long long factorial(int n) {
    if (n <= 1) {
        return 1;                    // base case
    }
    return n * factorial(n - 1);     // recursive call
}

int main(void) {
    int n;

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

    printf("Factorial of %d = %llu\n", n, factorial(n));
    return 0;
}

Output:

Output of the above program is

Enter a number: 6
Factorial of 6 = 720

How it works

  • factorial(6) calls factorial(5), and so on, until factorial(1) returns 1.
  • Then the answers are multiplied while the calls return: 1, 2, 6, 24, 120 and 720.

Read C Recursion.

Write a C program to swap two numbers using a function and pointers

Description: Write a function which swaps the values of two variables. The values must change in the main() function.

Hint:

  • Pass the addresses of the variables with &, and use * inside the function.

C program to swap two numbers using pointers

#include <stdio.h>

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

int main(void) {
    int x, y;

    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);

    swap(&x, &y);
    printf("After swapping: x = %d, y = %d\n", x, y);
    return 0;
}

Output:

Output of the above program is

Enter two numbers: 5 9
After swapping: x = 9, y = 5

How it works

  • The function gets the addresses of x and y, so it changes the original values.
  • With normal parameters (call by value), the function would swap only its own copies.

Read Call by Value and Reference.

Write a C program to store and print student details using a structure

Description: Take the roll number, name and marks of a student as input. Store them in a structure and print them.

Hint:

  • Make a structure with an int, a char array and a float. Use the dot operator to reach its members.

C program to store student details in a structure

#include <stdio.h>

struct Student {
    int roll;
    char name[30];
    float marks;
};

int main(void) {
    struct Student s;

    printf("Enter roll number, name and marks: ");
    scanf("%d", &s.roll);
    scanf("%29s", s.name);
    scanf("%f", &s.marks);

    printf("Roll: %d\n", s.roll);
    printf("Name: %s\n", s.name);
    printf("Marks: %.1f\n", s.marks);
    return 0;
}

Output:

Output of the above program is

Enter roll number, name and marks: 1
Robin
85.5
Roll: 1
Name: Robin
Marks: 85.5

How it works

  • The structure keeps three different types of data in one variable.
  • %29s limits the name to 29 characters, so it cannot go outside the array.

Read C Structures.

Write a C program to make a simple calculator using switch

Description: Take two numbers and an operator (+, -, *, /) as input. Print the result.

Hint:

  • Use a switch on the operator character. Check that the divisor is not zero before dividing.

C program for a simple calculator

#include <stdio.h>

int main(void) {
    float a, b;
    char op;

    printf("Enter number, operator, number: ");
    scanf("%f %c %f", &a, &op, &b);

    switch (op) {
        case '+': printf("Result = %.2f\n", a + b); break;
        case '-': printf("Result = %.2f\n", a - b); break;
        case '*': printf("Result = %.2f\n", a * b); break;
        case '/':
            if (b != 0) {
                printf("Result = %.2f\n", a / b);
            } else {
                printf("Division by zero is not allowed\n");
            }
            break;
        default:
            printf("Invalid operator\n");
    }
    return 0;
}

Output:

Output of the above program is

Enter number, operator, number: 12 / 5
Result = 2.40

How it works

  • The input 12 / 5 is read into a, op and b.
  • The case '/' runs and prints 2.40.
  • The default case handles any other character.

Read C Switch Statement.