Important C Programs for Practice

This page contains classic C programs commonly asked in lab exams, university examinations, and programming interviews. Each program demonstrates fundamental concepts and serves as building blocks for more complex applications.

šŸ’” Tip: Start by dry running each program on paper. Then try to modify it — for example, change Fibonacci to starting from 1, or make the prime number program print primes in a given range.

Number-based Programs

1. Fibonacci Series

Level: Easy

Generates Fibonacci sequence where each number is the sum of the two preceding ones. Essential for understanding loops, variables, and sequence generation.

/* C program to generate Fibonacci series */
#include <stdio.h>

int main(void) {
    int n, first = 0, second = 1, next;
    
    printf("Enter number of terms: ");
    scanf("%d", &n);
    
    printf("Fibonacci Series: ");
    for (int i = 0; i < n; i++) {
        if (i <= 1) {
            next = i;
        } else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d ", next);
    }
    
    return 0;
}

Concepts Used

  • Loops (for)
  • Variables and assignment
  • Sequence generation

Exam / Viva Tips

  • Be able to explain the first two terms (0 and 1).
  • Know how to modify the program to print only even terms.

2. Prime Number Check

Level: Medium

Checks if a number is prime using optimized trial division. Demonstrates loops, conditionals, and mathematical logic.

/* C program to check prime number */
#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    if (is_prime(num)) {
        printf("%d is a prime number.\n", num);
    } else {
        printf("%d is not a prime number.\n", num);
    }
    
    return 0;
}

Concepts Used

  • Functions
  • Conditional statements
  • Mathematical operations

Exam / Viva Tips

  • Explain why checking up to sqrt(n) is sufficient.
  • Modify to print all primes in a given range.

3. Palindrome Number

Level: Easy

Checks if a number reads the same forwards and backwards. Demonstrates digit extraction and number reversal using loops.

/* C program to check palindrome number */
#include <stdio.h>

int main() {
    int num, original, reversed = 0, remainder;
    
    printf("Enter a number: ");
    scanf("%d", &num);
    original = num;
    
    while (num != 0) {
        remainder = num % 10;
        reversed = reversed * 10 + remainder;
        num /= 10;
    }
    
    if (original == reversed) {
        printf("%d is a palindrome.\n", original);
    } else {
        printf("%d is not a palindrome.\n", original);
    }
    
    return 0;
}

// Example: 121, 1331 are palindromes

Concepts Used

  • While loop
  • Modulus operator (%)
  • Integer division

Exam / Viva Tips

  • Explain the digit extraction process.
  • Extend to check palindrome strings.

4. Factorial

Level: Easy

Calculates factorial of a number using both iterative and recursive approaches. Essential for understanding recursion and loops.

/* C program to calculate factorial */
#include <stdio.h>

// Recursive method
long long factorial_recursive(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial_recursive(n - 1);
}

// Iterative method
long long factorial_iterative(int n) {
    long long fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    if (num < 0) {
        printf("Factorial of negative number doesn't exist.\n");
    } else {
        printf("Factorial of %d = %lld\n", num, factorial_iterative(num));
        printf("Factorial (recursive) = %lld\n", factorial_recursive(num));
    }
    
    return 0;
}

Concepts Used

  • Recursion
  • Iteration
  • Function calls

Exam / Viva Tips

  • Compare iterative vs recursive approach.
  • Explain base case in recursion.

5. Armstrong Number

Level: Medium

Checks if a number is Armstrong (sum of digits raised to power of number of digits equals the number). Demonstrates digit manipulation and power calculations.

/* C program to check Armstrong number */
#include <stdio.h>
#include <math.h>

int main() {
    int num, original, remainder, result = 0, digits = 0;
    
    printf("Enter a number: ");
    scanf("%d", &num);
    original = num;
    
    // Count digits
    int temp = num;
    while (temp != 0) {
        digits++;
        temp /= 10;
    }
    
    // Calculate sum of digits raised to power of digits
    temp = num;
    while (temp != 0) {
        remainder = temp % 10;
        result += pow(remainder, digits);
        temp /= 10;
    }
    
    if (result == original) {
        printf("%d is an Armstrong number.\n", original);
    } else {
        printf("%d is not an Armstrong number.\n", original);
    }
    
    return 0;
}

// Example: 153 = 1^3 + 5^3 + 3^3 = 153

Concepts Used

  • Math library (pow)
  • Digit counting
  • While loops

Exam / Viva Tips

  • Explain the Armstrong number concept.
  • Find all Armstrong numbers in a range.

Array & Matrix Programs

6. Matrix Addition

Level: Medium

Adds two matrices element-wise. Demonstrates 2D arrays, nested loops, and matrix operations.

/* C program for matrix addition */
#include <stdio.h>

int main() {
    int rows, cols;
    printf("Enter rows and columns: ");
    scanf("%d %d", &rows, &cols);
    
    int matrix1[10][10], matrix2[10][10], sum[10][10];
    
    printf("Enter elements of first matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &matrix1[i][j]);
        }
    }
    
    printf("Enter elements of second matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &matrix2[i][j]);
        }
    }
    
    // Add matrices
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            sum[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    
    printf("Sum of matrices:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", sum[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Concepts Used

  • 2D arrays
  • Nested loops
  • Matrix operations

Exam / Viva Tips

  • Extend to matrix multiplication.
  • Implement matrix transpose.

7. Matrix Multiplication

Level: Hard

Multiplies two matrices using triple nested loops. Demonstrates complex matrix operations and dimension validation.

/* C program for matrix multiplication */
#include <stdio.h>

int main() {
    int m, n, p, q;
    printf("Enter dimensions of first matrix (m x n): ");
    scanf("%d %d", &m, &n);
    printf("Enter dimensions of second matrix (p x q): ");
    scanf("%d %d", &p, &q);
    
    if (n != p) {
        printf("Matrix multiplication not possible!\n");
        return 1;
    }
    
    int matrix1[10][10], matrix2[10][10], result[10][10];
    
    // Input matrices
    printf("Enter first matrix:\n");
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &matrix1[i][j]);
        }
    }
    
    printf("Enter second matrix:\n");
    for (int i = 0; i < p; i++) {
        for (int j = 0; j < q; j++) {
            scanf("%d", &matrix2[i][j]);
        }
    }
    
    // Multiply matrices
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < q; j++) {
            result[i][j] = 0;
            for (int k = 0; k < n; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }
    
    // Display result
    printf("Result matrix:\n");
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < q; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Concepts Used

  • Triple nested loops
  • Dimension checking
  • Matrix operations

Exam / Viva Tips

  • Explain the multiplication algorithm.
  • Discuss time complexity (O(n³)).

8. Linear Search

Level: Easy

Searches for an element in an array by checking each element sequentially. Simple but useful for understanding array traversal.

/* C program for linear search */
#include <stdio.h>

int linear_search(int arr[], int size, int key) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == key) {
            return i;  // Return index if found
        }
    }
    return -1;  // Return -1 if not found
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    int key;
    
    printf("Enter element to search: ");
    scanf("%d", &key);
    
    int result = linear_search(arr, size, key);
    if (result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found\n");
    }
    
    return 0;
}

Concepts Used

  • Arrays
  • Functions
  • Linear traversal

Exam / Viva Tips

  • Compare with binary search.
  • Discuss time complexity (O(n)).

9. Binary Search

Level: Medium

Efficient search algorithm for sorted arrays using divide-and-conquer approach. Demonstrates binary search logic and efficiency.

/* C program for binary search */
#include <stdio.h>

int binary_search(int arr[], int left, int right, int key) {
    while (left <= right) {
        int mid = left + (right - left) / 2;
        
        if (arr[mid] == key) {
            return mid;
        }
        
        if (arr[mid] < key) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;  // Not found
}

int main() {
    int arr[] = {10, 20, 30, 40, 50, 60, 70};
    int size = sizeof(arr) / sizeof(arr[0]);
    int key;
    
    printf("Enter element to search: ");
    scanf("%d", &key);
    
    int result = binary_search(arr, 0, size - 1, key);
    if (result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found\n");
    }
    
    return 0;
}

// Note: Array must be sorted for binary search

Concepts Used

  • Divide and conquer
  • Sorted arrays
  • While loop

Exam / Viva Tips

  • Explain why array must be sorted.
  • Compare time complexity with linear search.

10. Bubble Sort

Level: Medium

Simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them. Easy to understand.

/* C program for bubble sort */
#include <stdio.h>

void bubble_sort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    printf("Original array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    bubble_sort(arr, size);
    
    printf("Sorted array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Concepts Used

  • Nested loops
  • Swapping elements
  • Array manipulation

Exam / Viva Tips

  • Explain the sorting process step by step.
  • Discuss time complexity (O(n²)).

11. Selection Sort

Level: Medium

Sorts array by repeatedly finding the minimum element from unsorted part and placing it at the beginning. Simpler than other algorithms.

/* C program for selection sort */
#include <stdio.h>

void selection_sort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        int min_idx = i;
        for (int j = i + 1; j < size; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }
        // Swap
        int temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
    }
}

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    selection_sort(arr, size);
    
    printf("Sorted array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Concepts Used

  • Finding minimum
  • Swapping
  • Nested loops

Exam / Viva Tips

  • Compare with bubble sort.
  • Explain the selection process.

File Handling Programs

12. Writing to File

Level: Medium

Demonstrates how to create and write data to a file using fprintf(). Essential for data persistence in C programs.

/* C program to write to file */
#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("data.txt", "w");
    
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    
    fprintf(fp, "Hello, World!\n");
    fprintf(fp, "This is a file handling example.\n");
    fprintf(fp, "Number: %d\n", 42);
    
    fclose(fp);
    printf("Data written to file successfully.\n");
    
    return 0;
}

Concepts Used

  • FILE pointer
  • fopen() and fclose()
  • fprintf()

Exam / Viva Tips

  • Always check if file opened successfully.
  • Explain different file modes ("w", "a", "r+").

13. Reading from File

Level: Medium

Reads data from a file using fgets() and displays it. Demonstrates file reading operations and error handling.

/* C program to read from file */
#include <stdio.h>

int main() {
    FILE *fp;
    char buffer[100];
    
    fp = fopen("data.txt", "r");
    
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    
    printf("File contents:\n");
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer);
    }
    
    fclose(fp);
    return 0;
}

Concepts Used

  • File reading
  • fgets() function
  • Buffer handling

Exam / Viva Tips

  • Explain why we use fgets() vs fscanf().
  • Demonstrate reading line by line.

Pointer / Structure Programs

14. Swapping using Pointers

Level: Medium

Swaps two numbers using pointers to demonstrate call by reference. Fundamental concept for understanding pointer operations.

/* C program to swap using pointers */
#include <stdio.h>

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

int main() {
    int x = 10, y = 20;
    
    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After swap: x = %d, y = %d\n", x, y);
    
    return 0;
}

Concepts Used

  • Pointers
  • Call by reference
  • Dereferencing

Exam / Viva Tips

  • Explain call by value vs call by reference.
  • Show how pointers modify original variables.

15. Array using Pointers

Level: Medium

Accesses array elements using pointer arithmetic. Demonstrates the relationship between arrays and pointers in C.

/* C program to access array using pointers */
#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;  // Points to first element
    
    printf("Array elements using pointer:\n");
    for (int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, *(ptr + i));
    }
    
    printf("\nArray elements using pointer arithmetic:\n");
    for (int i = 0; i < 5; i++) {
        printf("Value at address %p: %d\n", (ptr + i), *(ptr + i));
    }
    
    return 0;
}

Concepts Used

  • Pointer arithmetic
  • Array-pointer relationship
  • Address printing

Exam / Viva Tips

  • Explain how arr[i] relates to *(arr + i).
  • Demonstrate pointer increment operations.

What to Practice Next

  • Modify programs to handle invalid input and add error checking.
  • Convert iterative solutions to recursive versions and vice versa.
  • Combine multiple concepts (e.g., use arrays with functions, pointers with structures).
  • Add input validation and boundary checks to all programs.
  • Create menu-driven programs that combine multiple operations.
  • Practice string manipulation programs (palindrome strings, string reversal).
  • Implement more complex sorting algorithms (Insertion Sort, Quick Sort).

Program Categories Summary

CategoryProgramsDifficulty
Number-basedFibonacci, Prime, Palindrome, Factorial, ArmstrongEasy to Medium
Array & MatrixMatrix Addition/Multiplication, Linear/Binary Search, Bubble/Selection SortMedium to Hard
File HandlingWriting to File, Reading from FileMedium
Pointers & StructuresSwapping using Pointers, Array using PointersMedium

Frequently Asked Questions

Q1: How should I practice these programs?

Start with easy programs (Fibonacci, factorial), understand the logic, then move to medium difficulty. Don't copy-paste - type code yourself to learn. Dry run programs on paper first, then code. Modify programs (e.g., print even Fibonacci numbers, find primes in range). Practice regularly, solve variations, and combine concepts.

Q2: Which programs are most important for exams?

All programs are important, but focus on: array operations (searching, sorting), string manipulation, matrix operations, file handling, and structure programs. These appear frequently in exams. Also practice number-based programs (prime, palindrome, factorial) as they test fundamental concepts.

Q3: How do I debug programs that don't work?

Add printf statements to check variable values at different points. Verify input is correct. Check array bounds, pointer initialization, and loop conditions. Use compiler warnings (-Wall -Wextra). Trace through code manually. Start with simple test cases. Use debugger (GDB) for complex issues. Check for common errors: missing semicolons, wrong operators, off-by-one errors.

Q4: Should I memorize these programs?

Don't memorize - understand the logic and algorithm. Once you understand how a program works, you can write it from scratch. Focus on understanding patterns: how loops work, how arrays are traversed, how conditions are checked. Understanding enables you to solve variations and new problems.

Q5: How can I improve my programming speed?

Practice regularly - code daily. Start with simple programs and gradually increase complexity. Learn common patterns and algorithms. Type code yourself (don't copy-paste). Practice writing code on paper for exams. Time yourself while coding. Review and refactor your code. The more you practice, the faster you become.

Q6: What's the difference between iterative and recursive solutions?

Iterative uses loops, recursive uses function calls. Iterative is usually faster and uses less memory. Recursive is more elegant for some problems (tree traversal, divide-and-conquer) but can cause stack overflow for large inputs. Practice both - understand when to use each. Many problems can be solved either way.

Q7: How do I prepare for lab exams with these programs?

Practice writing complete, working programs from scratch. Time yourself. Practice explaining your code. Understand algorithms, not just syntax. Be able to modify programs (e.g., change sorting order, add features). Practice debugging. Review common errors. Be confident with array operations, string functions, and file handling.

Q8: Can I use these programs in my projects?

Yes, but modify and adapt them for your needs. Add error checking, input validation, and proper documentation. Combine multiple programs to create larger applications. Use these as building blocks. For example, combine file handling with structures to create a student management system. Always understand the code before using it.

Conclusion

These programs cover fundamental C programming concepts that are essential for any programmer. Mastering these programs provides a strong foundation for more advanced programming and problem-solving. Each program demonstrates important concepts and algorithms used in real-world applications.

Regular practice is key to becoming proficient in C programming. Don't just read these programs - write them yourself, modify them, and create variations. Understanding the logic behind each program is more important than memorizing code. As you practice, you'll develop problem-solving skills and programming intuition that will help you tackle new challenges.

Related Links

šŸ”¹ Author: Dr. J. Siva Ramakrishna

šŸ”¹ Institution: Narayana Engineering College, Gudur

šŸ”¹ Last Updated: 9 January 2026