C Top Exercises

The most popular C exercises: a calculator with switch, factorial, prime numbers, Fibonacci, palindrome, bubble sort, leap year and swapping two variables.

Write a C program to check whether a number is even or odd

Description: Take a number as input. Print if it is even or odd.

Hint:

  • A number is even when the remainder of the division by 2 is zero.

C program to check even or odd

#include <stdio.h>

int main(void) {
    int n;

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

    if (n % 2 == 0) {
        printf("%d is even\n", n);
    } else {
        printf("%d is odd\n", n);
    }
    return 0;
}

Output:

Output of the above program is

Enter a number: 27
27 is odd

How it works

  • 27 % 2 gives 1, so the number is odd.
  • For negative numbers it also works, because -4 % 2 is 0.

Write a C program to swap the values of two variables using a third variable

Description: Take two numbers as input and swap their values using a third variable.

Hint:

  • Save the first value in a temporary variable, then copy the second into the first, and last put the temporary value in the second.

C program to swap two numbers using a third variable

#include <stdio.h>

int main(void) {
    int a, b, temp;

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

    temp = a;
    a = b;
    b = temp;

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

Output:

Output of the above program is

Enter two numbers: 10 20
After swapping: a = 20, b = 10

How it works

  • temp = a saves 10, a = b makes a = 20, and b = temp makes b = 10.
  • Without temp the first value would be lost.

Write a C program to check whether an alphabet is vowel or consonant

Description: Take an alphabet as input. Print if it is a vowel or a consonant.

Hint:

  • The vowels are a, e, i, o, u (in small and capital letters). Convert the letter to lower case with tolower() to keep the code short.

C program to check vowel or consonant

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

int main(void) {
    char ch;

    printf("Enter an alphabet: ");
    scanf(" %c", &ch);

    switch (tolower(ch)) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            printf("%c is a vowel\n", ch);
            break;
        default:
            if (isalpha(ch)) {
                printf("%c is a consonant\n", ch);
            } else {
                printf("%c is not an alphabet\n", ch);
            }
    }
    return 0;
}

Output:

Output of the above program is

Enter an alphabet: E
E is a vowel

How it works

  • tolower('E') gives 'e', which matches a vowel case.
  • The space before %c in scanf(" %c") skips the white spaces, like the Enter key.
  • isalpha() checks that the input is a letter.

Read C Switch Statement.

Write a C program to find the maximum number between three numbers

Description: Take three numbers as input and print the largest one.

Hint:

  • Compare the numbers using the >= and && operators.

C program to find the largest of three numbers

#include <stdio.h>

int main(void) {
    int a, b, c, max;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    if (a >= b && a >= c) {
        max = a;
    } else if (b >= a && b >= c) {
        max = b;
    } else {
        max = c;
    }
    printf("Largest = %d\n", max);
    return 0;
}

Output:

Output of the above program is

Enter three numbers: 12 45 30
Largest = 45

How it works

  • We check if a is greater than or equal to both others. If not, we check b, and otherwise c must be the largest.
  • Using >= also works when two numbers are equal.

Write a C program to check whether a year is a leap year or not

Description: Take a year as input. Print if it is a leap year or not.

Hint:

  • A year is a leap year if it is divisible by 400, or it is divisible by 4 but not by 100.

C program to check for a leap year

#include <stdio.h>

int main(void) {
    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;
}

Output:

Output of the above program is

Enter a year: 2024
2024 is a leap year

How it works

  • 2024 is divisible by 4 and not by 100, so it is a leap year.
  • 1900 is divisible by 100 but not by 400, so it is not. The year 2000 is divisible by 400, so it is.

Read C Operators for the logical operators.

Write a C program to find the factorial of a number

Description: Take a number as input and print its factorial. Factorial of n is 1 x 2 x 3 x ... x n.

Hint:

  • Start with fact = 1 and multiply it by each number from 1 to n. Use unsigned long long for bigger values.

C program to find the factorial

#include <stdio.h>

int main(void) {
    int n;
    unsigned long long fact = 1;

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

    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    printf("Factorial of %d = %llu\n", n, fact);
    return 0;
}

Output:

Output of the above program is

Enter a number: 5
Factorial of 5 = 120

How it works

  • fact becomes 1, 2, 6, 24 and finally 120.
  • Factorial of 0 is 1, and our loop gives 1 for 0, so it is correct.
  • The type unsigned long long holds values up to 20! only.

Read C Recursion for the recursive way.

Write a C program to print the Fibonacci series

Description: Take the number of terms as input. Print that many terms of the Fibonacci series: 0, 1, 1, 2, 3, 5, 8 …

Hint:

  • Each term is the sum of the two terms before it.

C program to print the Fibonacci series

#include <stdio.h>

int main(void) {
    int n, a = 0, b = 1, next;

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

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

Output:

Output of the above program is

Enter number of terms: 8
0 1 1 2 3 5 8 13

How it works

  • We start with a = 0 and b = 1.
  • In each round we print a, then move forward: a takes the value of b, and b takes the new sum.

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

Description: Take a number as input. Print if it is a palindrome (it reads the same from both sides), like 121.

Hint:

  • Reverse the number, and compare it with the original.

C program to check a palindrome number

#include <stdio.h>

int main(void) {
    int n, original, reversed = 0;

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

    while (n > 0) {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }

    if (original == reversed) {
        printf("%d is a palindrome\n", original);
    } else {
        printf("%d is not a palindrome\n", original);
    }
    return 0;
}

Output:

Output of the above program is

Enter a number: 121
121 is a palindrome

How it works

  • We keep a copy in original, because the loop changes n.
  • 121 reversed is 121, so both are equal.

Read Reverse a Number.

Write a C program to check whether a number is prime or not

Description: Take a number as input. Print if it is a prime number. A prime number has only two factors, 1 and itself.

Hint:

  • Try to divide the number by 2, 3, 4 … Stop when a divisor is found, or when the divisor is more than the square root.

C program to check a prime number

#include <stdio.h>

int main(void) {
    int n, isPrime = 1;

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

    if (n < 2) {
        isPrime = 0;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }

    if (isPrime) {
        printf("%d is a prime number\n", n);
    } else {
        printf("%d is not a prime number\n", n);
    }
    return 0;
}

Output:

Output of the above program is

Enter a number: 29
29 is a prime number

How it works

  • Numbers less than 2 are not prime.
  • If n has a divisor, it has one which is not more than its square root. So the loop stops at i * i <= n.
  • break ends the loop as soon as a divisor is found.

Write a C program to find the largest element in an array

Description: Take 5 numbers in an array and print the largest one.

Hint:

  • Assume the first element is the largest. Then compare the others, and update the value if a bigger one is found.

C program to find the largest element in an array

#include <stdio.h>

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

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

    max = a[0];
    for (int i = 1; i < 5; i++) {
        if (a[i] > max) {
            max = a[i];
        }
    }
    printf("Largest = %d\n", max);
    return 0;
}

Output:

Output of the above program is

Enter 5 numbers: 23
91
45
67
12
Largest = 91

How it works

  • max starts as 23. When 91 is found, it is bigger, so max becomes 91. No later value is bigger.
  • For the smallest element, change > to <.

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 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 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 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.