Skip to content
StudyFame

Important C Programs for Exams

Lab exams and written papers ask a small set of programs again and again: prime numbers, palindromes, Armstrong numbers, Fibonacci, GCD, sorting, matrices and string operations. If you can write these from memory, explain the logic and predict the output, you are ready for most C practical exams.

This page gives 10 must-know programs, each tested with its output and a short logic note. For more practice, the C Program section has many more examples with step-by-step explanations.

What You Will Learn

  • The 10 most frequently asked C programs.
  • The core logic (algorithm) behind each one.
  • Number programs using % 10 and / 10.
  • Array programs: maximum, sorting, matrices.
  • String programs without library functions.
  • How to present a program in an exam for full marks.

Important C Programs for Exams Explained

Exam method: For each program, write the aim, the algorithm in 3–5 steps, the program with comments, and the output for a sample input. Examiners give marks for each part, so even a small mistake in code doesn't cost all the marks if the algorithm is right.

Memory trick: Most number programs use the "digit peeler": n % 10 peels off the last digit and n / 10 throws it away. Reverse, palindrome, Armstrong, sum of digits and count of digits are all the same loop with a different action on each digit.

Number Programs

Program 1: Prime Number Check

#include <stdio.h>

int is_prime(int n)
{
    int i;
    if (n < 2)
        return 0;
    for (i = 2; i * i <= n; i++)     /* check divisors up to sqrt(n) */
        if (n % i == 0)
            return 0;
    return 1;
}

int main(void)
{
    int n;
    printf("Primes up to 50: ");
    for (n = 1; n <= 50; n++)
        if (is_prime(n))
            printf("%d ", n);
    printf("\n");
    return 0;
}

Output

Primes up to 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

Code Explanation

  1. A prime has exactly two divisors, 1 and itself; 0 and 1 are not prime.
  2. If n has a divisor bigger than √n, it also has one smaller than √n, so checking i * i <= n is enough. This is much faster than checking up to n − 1.
  3. The function returns as soon as it finds a divisor. More versions: Prime Number Program in C.

Program 2: Reverse a Number and Check Palindrome

#include <stdio.h>

int reverse(int n)
{
    int rev = 0;
    while (n > 0)
    {
        rev = rev * 10 + n % 10;   /* append last digit */
        n /= 10;                   /* remove last digit */
    }
    return rev;
}

int main(void)
{
    int nums[] = {12321, 4567, 1001};
    int i;
    for (i = 0; i < 3; i++)
        printf("%d reversed is %d -> %s\n", nums[i], reverse(nums[i]),
               reverse(nums[i]) == nums[i] ? "palindrome" : "not palindrome");
    return 0;
}

Output

12321 reversed is 12321 -> palindrome
4567 reversed is 7654 -> not palindrome
1001 reversed is 1001 -> palindrome

Logic: peel digits from the right and build the reversed number; a palindrome equals its reverse. See also Palindrome Program in C.

Program 3: Armstrong Numbers

#include <stdio.h>

int count_digits(int n)
{
    int c = 0;
    do { c++; n /= 10; } while (n > 0);
    return c;
}

int is_armstrong(int n)
{
    int digits = count_digits(n), sum = 0, t = n, d, p, i;
    while (t > 0)
    {
        d = t % 10;
        for (p = 1, i = 0; i < digits; i++)
            p *= d;                /* d raised to the number of digits */
        sum += p;
        t /= 10;
    }
    return sum == n;
}

int main(void)
{
    int n;
    printf("Armstrong numbers up to 1000: ");
    for (n = 1; n <= 1000; n++)
        if (is_armstrong(n))
            printf("%d ", n);
    printf("\n");
    return 0;
}

Output

Armstrong numbers up to 1000: 1 2 3 4 5 6 7 8 9 153 370 371 407 

Logic: a number is Armstrong if the sum of each digit raised to the number of digits equals the number: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27. Integer powers avoid the rounding problems of pow(). More: Armstrong Number in C.

Program 4: Fibonacci Series (Iterative)

#include <stdio.h>

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

    printf("First %d terms: ", n);
    for (i = 0; i < n; i++)
    {
        printf("%ld ", a);
        next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}

Output

First 12 terms: 0 1 1 2 3 5 8 13 21 34 55 89 

Logic: each term is the sum of the previous two; keep only the last two values and slide them forward. This is faster than recursion. Recursive version: Fibonacci Using Recursion.

Program 5: GCD and LCM (Euclid's Algorithm)

#include <stdio.h>

int gcd(int a, int b)
{
    while (b != 0)
    {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main(void)
{
    int pairs[3][2] = {{12, 18}, {17, 5}, {48, 180}};
    int i, a, b, g;

    for (i = 0; i < 3; i++)
    {
        a = pairs[i][0];
        b = pairs[i][1];
        g = gcd(a, b);
        printf("GCD(%d, %d) = %d, LCM = %d\n", a, b, g, a / g * b);
    }
    return 0;
}

Output

GCD(12, 18) = 6, LCM = 36
GCD(17, 5) = 1, LCM = 85
GCD(48, 180) = 12, LCM = 720

Logic: GCD(a, b) = GCD(b, a % b) until b becomes 0. Then LCM = a × b / GCD; writing a / g * b divides first to avoid overflow. More: GCD of Two Numbers in C.

How to Present a Program in the Exam

AIM       : To check whether a number is prime.
ALGORITHM : 1. Read n.
            2. If n < 2, it is not prime.
            3. For i = 2 while i*i <= n: if n % i == 0, it is not prime.
            4. Otherwise it is prime.
PROGRAM   : (neat, indented, with comments)
OUTPUT    : Enter a number: 29
            29 is a prime number.

Writing the algorithm first also helps you avoid mistakes in the code.

Array and String Programs

Program 6: Largest and Second Largest in an Array

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

int main(void)
{
    int a[] = {45, 78, 12, 89, 34, 89, 67};
    int n = sizeof a / sizeof a[0], i;
    int first = INT_MIN, second = INT_MIN;

    for (i = 0; i < n; i++)
    {
        if (a[i] > first)
        {
            second = first;
            first = a[i];
        }
        else if (a[i] > second && a[i] != first)
            second = a[i];
    }
    printf("Largest = %d, Second largest = %d\n", first, second);
    return 0;
}

Output

Largest = 89, Second largest = 78

Logic: one pass; when a new largest appears, the old largest becomes the second. The a[i] != first check stops the duplicate 89 from becoming the second largest.

Program 7: Bubble Sort

#include <stdio.h>

int main(void)
{
    int a[] = {64, 25, 12, 22, 11};
    int n = 5, i, j, t, swapped;

    for (i = 0; i < n - 1; i++)
    {
        swapped = 0;
        for (j = 0; j < n - 1 - i; j++)
            if (a[j] > a[j + 1])
            {
                t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
                swapped = 1;
            }
        if (!swapped)
            break;                 /* already sorted */
    }
    printf("Sorted: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output

Sorted: 11 12 22 25 64 

Logic: compare neighbours and swap if out of order; after each pass the largest remaining element "bubbles" to the end. The swapped flag stops early if no swaps happen. Details: Sorting an Array in C.

Program 8: Matrix Multiplication

#include <stdio.h>

int main(void)
{
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
    int c[2][2] = {{0}};
    int i, j, k;

    for (i = 0; i < 2; i++)
        for (j = 0; j < 2; j++)
            for (k = 0; k < 3; k++)
                c[i][j] += a[i][k] * b[k][j];

    printf("Result (2 x 2):\n");
    for (i = 0; i < 2; i++)
        printf("%4d %4d\n", c[i][0], c[i][1]);
    return 0;
}

Output

Result (2 x 2):
  58   64
 139  154

Logic: multiplying an m × n matrix by an n × p matrix gives m × p; each c[i][j] is the sum of row i of A times column j of B. c[0][0] = 1×7 + 2×9 + 3×11 = 58. Columns of A must equal rows of B.

Program 9: String Palindrome Without Library Functions

#include <stdio.h>

int length(const char *s)
{
    int n = 0;
    while (s[n] != '\0')
        n++;
    return n;
}

int is_palindrome(const char *s)
{
    int i = 0, j = length(s) - 1;
    while (i < j)
        if (s[i++] != s[j--])
            return 0;
    return 1;
}

int main(void)
{
    const char *words[] = {"madam", "level", "hello", "a"};
    int i;
    for (i = 0; i < 4; i++)
        printf("%-6s length %d -> %s\n", words[i], length(words[i]),
               is_palindrome(words[i]) ? "palindrome" : "not palindrome");
    return 0;
}

Output

madam  length 5 -> palindrome
level  length 5 -> palindrome
hello  length 5 -> not palindrome
a      length 1 -> palindrome

Logic: compare characters from both ends moving inwards; stop at the first mismatch. Writing your own length() shows the examiner you understand '\0'.

Program 10: Count Vowels, Consonants, Digits and Spaces

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

int main(void)
{
    const char *s = "C was made in 1972 at Bell Labs";
    int vowels = 0, consonants = 0, digits = 0, spaces = 0, i;
    char ch;

    for (i = 0; s[i] != '\0'; i++)
    {
        ch = (char) tolower((unsigned char) s[i]);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            vowels++;
        else if (isalpha((unsigned char) ch))
            consonants++;
        else if (isdigit((unsigned char) ch))
            digits++;
        else if (ch == ' ')
            spaces++;
    }
    printf("Vowels: %d, Consonants: %d, Digits: %d, Spaces: %d\n",
           vowels, consonants, digits, spaces);
    return 0;
}

Output

Vowels: 7, Consonants: 13, Digits: 4, Spaces: 7

Logic: convert each character to lower case, then classify it with simple checks and ctype.h functions.

Important Points to Remember

  • % 10 gives the last digit, / 10 removes it: the base of most number programs.
  • Prime check: loop while i * i <= n; 0 and 1 are not prime.
  • GCD by Euclid: gcd(a, b) = gcd(b, a % b); LCM = a / gcd × b.
  • Bubble sort: neighbour swaps, n − 1 passes, stop early if no swap.
  • Matrix multiplication needs columns of A = rows of B; three nested loops.
  • Always show aim, algorithm, program and output in exams.

Common Mistakes Beginners Make

MistakeWhat happensFix
Reversing n directly, then comparing with nn is 0 after the loop; palindrome check failsWork on a copy, keep the original
Calling 1 a primeWrong answerReturn 0 for n < 2
Not initialising sum/result to 0 (or 1 for products)Garbage resultsInitialise before the loop
Wrong inner loop limit in bubble sortReads a[n] out of boundsj < n - 1 - i
Not resetting c[i][j] = 0 in matrix multiplicationGarbage added to resultsInitialise c with zeros

Program Practice Questions

  1. Write the algorithm to find the sum of digits of a number.
  2. Why is it enough to check divisors up to √n for a prime test?
  3. What is the output of the GCD program for 20 and 8?
  4. How many comparisons does bubble sort make in the worst case for n elements?
  5. Can a 2 × 3 matrix be multiplied by a 2 × 3 matrix? Why?
Show answers
  1. sum = 0; while n > 0: sum += n % 10; n /= 10; print sum.
  2. Divisors come in pairs (d, n/d); one of each pair is at most √n.
  3. GCD(20, 8) = 4, LCM = 40.
  4. n(n − 1)/2.
  5. No: the first matrix has 3 columns but the second has 2 rows; they must be equal.

Coding Exercise

Write a program that prints all perfect numbers up to 10000. A perfect number equals the sum of its proper divisors (e.g. 6 = 1 + 2 + 3).

Show solution
#include <stdio.h>

int is_perfect(int n)
{
    int sum = 1, i;                /* 1 divides every n > 1 */
    if (n < 2)
        return 0;
    for (i = 2; i * i <= n; i++)
        if (n % i == 0)
        {
            sum += i;
            if (i != n / i)
                sum += n / i;      /* add the pair divisor */
        }
    return sum == n;
}

int main(void)
{
    int n;
    printf("Perfect numbers up to 10000: ");
    for (n = 1; n <= 10000; n++)
        if (is_perfect(n))
            printf("%d ", n);
    printf("\n");
    return 0;
}
Perfect numbers up to 10000: 6 28 496 8128 

Quick Quiz: Important Programs (MCQ)

  1. 1234 % 10 gives:

    A) 1   B) 4   C) 123   D) 0

  2. 153 is an Armstrong number because:

    A) 1 + 5 + 3 = 9   B) 1³ + 5³ + 3³ = 153   C) It is prime   D) It is odd

  3. GCD(36, 48) is:

    A) 6   B) 12   C) 4   D) 144

  4. The 8th Fibonacci term (starting 0, 1) is:

    A) 8   B) 13   C) 21   D) 5

  5. Multiplying a 3 × 2 matrix by a 2 × 4 matrix gives a:

    A) 3 × 4 matrix   B) 2 × 2 matrix   C) 4 × 3 matrix   D) Not possible

Show answers
  1. B: 4.
  2. B: 1³ + 5³ + 3³ = 153.
  3. B: 12.
  4. B: 13 (0 1 1 2 3 5 8 13).
  5. A: 3 × 4.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Digit peelern % 10 last digit, n / 10 remove it
PrimeDivisors up to √n; 0, 1 not prime
ArmstrongSum of digitscount = n (153, 370, 371, 407)
Fibonaccinext = a + b, slide a, b
GCD / LCMEuclid; LCM = a / gcd × b
Bubble sortNeighbour swaps, O(n²)
Matrix A×Bcols(A) = rows(B)

Frequently asked questions

Which C programs are most important for exams?
Prime, palindrome, Armstrong, Fibonacci, factorial, GCD/LCM, array max, bubble sort, matrix multiplication and string programs.
How do I remember so many programs?
Learn the patterns (digit peeler, two-pointer, nested loops), not the code line by line.
What should I write along with a program in an exam?
The aim, algorithm, commented program and sample output.

Remember

  • Learn patterns, not lines.
  • Aim, algorithm, program, output: every time.

Next Topic

Next lesson: C Programming MCQs. You will test yourself with C programming MCQs covering the whole tutorial.