C Programs

C Programming – Additional Programs


Programs at a Glance

This section lists the programs covering Number Systems, Expressions, Strings, Files, Pointers, Searching and Sorting in C. Click on a program title to jump directly to its detailed explanation.

  1. Binary Equivalent of a Number (0–255)
  2. Evaluation of Mathematical Expression
  3. Sum of Geometric Progression
  4. Roman Numeral to Decimal (I–L)
  5. Decimal to Roman (1–50)
  6. String Insertion Using Function
  7. Merge Two Files
  8. Reverse Array Using Pointer
  9. Sum of Array Using Pointer
  10. Insertion Sort (Ascending)

1. Binary Equivalent of a Number (0–255)


Problem Statement

Write a C program to display the binary equivalent of a given positive number between 0 and 255.

Student-Friendly Algorithm
  1. Start the program.
  2. Read an integer n in the range 0–255 from the user.
  3. Declare an integer array bin[8] to store 8 binary digits.
  4. For positions from 7 down to 0:
    • Store n % 2 (remainder when divided by 2) in bin[i].
    • Update n = n / 2 to remove the last bit.
  5. Print all 8 elements of bin from index 0 to 7 as the binary representation.
  6. Stop the program.
C Program

#include <stdio.h>

int main() {
    int n, bin[8], i;

    printf("Enter number (0-255):\n");
    scanf("%d", &n);

    for (i = 7; i >= 0; i--) {
        bin[i] = n % 2;
        n /= 2;
    }

    printf("Binary: ");
    for (i = 0; i < 8; i++)
        printf("%d", bin[i]);

    return 0;
}
  
Sample Output

Enter number (0-255):
13
Binary: 00001101
  
Explanation

The program repeatedly divides the number by 2 and stores the remainders, which correspond to binary digits (0 or 1). By filling the array from the last index downwards and then printing from the first index upwards, the bits appear in the correct most-significant-bit to least-significant-bit order.

2. Evaluation of Mathematical Expression


Problem Statement

Write a C program to evaluate the expression:
1 − x/2 + x²/4 − x³/6, where x is a fractional value.

Student-Friendly Algorithm
  1. Start the program.
  2. Read a fractional (floating-point) value x from the user.
  3. Use the formula 1 - x/2 + x²/4 - x³/6 to compute the result.
  4. Implement powers of x using the pow() function.
  5. Store the final result in a floating-point variable.
  6. Display the result up to three decimal places.
  7. Stop the program.
C Program

#include <stdio.h>
#include <math.h>

int main() {
    float x, result;

    printf("Enter value of x:\n");
    scanf("%f", &x);

    result = 1 - x / 2 + pow(x, 2) / 4 - pow(x, 3) / 6;

    printf("Result = %.3f\n", result);
    return 0;
}
  
Sample Output

Enter value of x:
2.0
Result = -0.333
  
Explanation

The program translates the mathematical expression directly into C using arithmetic operators and the library function pow() for and . The final value is printed with three digits after the decimal point using the format specifier %.3f.

3. Sum of Geometric Progression


Problem Statement

Write a C program to compute the sum of the geometric progression:
1 + x + x² + x³ + … + xⁿ

Student-Friendly Algorithm
  1. Start the program.
  2. Read a real number x (the common ratio) and integer n (highest power).
  3. Initialize sum = 0.
  4. For each exponent i from 0 to n:
    • Compute the term pow(x, i).
    • Add this term to sum.
  5. Display the final value of sum.
  6. Stop the program.
C Program

#include <stdio.h>
#include <math.h>

int main() {
    int n, i;
    float x, sum = 0;

    printf("Enter x and n:\n");
    scanf("%f %d", &x, &n);

    for (i = 0; i <= n; i++)
        sum += pow(x, i);

    printf("Sum = %.2f\n", sum);
    return 0;
}
  
Sample Output

Enter x and n:
2 3
Sum = 15.00
  
Explanation

Each term of the geometric progression is generated as x raised to the power i, starting from i = 0 (which gives 1). These terms are accumulated in sum, so the loop implements the series 1 + x + x² + … + xⁿ term by term.

4. Roman Numeral to Decimal (I–L)


Problem Statement

Write a C program to convert a Roman numeral ranging from I to L into its decimal equivalent.

Student-Friendly Algorithm
  1. Start the program.
  2. Read a Roman numeral string containing symbols I, V, X or L.
  3. Initialize a variable val = 0 to store the decimal value.
  4. Scan the string from left to right.
  5. For each character, add the corresponding value:
    • I → 1, V → 5, X → 10, L → 50.
  6. Display the final decimal value stored in val.
  7. Stop the program.
C Program

#include <stdio.h>

int main() {
    char r[20];
    int i, val = 0;

    printf("Enter Roman numeral:\n");
    scanf("%19s", r);

    for (i = 0; r[i] != '\0'; i++) {
        if (r[i] == 'I') val += 1;
        else if (r[i] == 'V') val += 5;
        else if (r[i] == 'X') val += 10;
        else if (r[i] == 'L') val += 50;
    }

    printf("Decimal = %d\n", val);
    return 0;
}
  
Sample Output

Enter Roman numeral:
XXIV
Decimal = 26
  
Explanation

Each Roman symbol is mapped to a fixed decimal value and these values are simply added to obtain the result. For the basic range I–L and simple combinations, this additive approach is sufficient, though more advanced subtraction cases (like IV = 4) are not handled here.

5. Decimal to Roman (1–50)


Problem Statement

Write a C program to convert a number ranging from 1 to 50 into its Roman equivalent.

Student-Friendly Algorithm
  1. Start the program.
  2. Read an integer n (1–50).
  3. While n ≥ 50, print ‘L’ and subtract 50.
  4. While n ≥ 10, print ‘X’ and subtract 10.
  5. While n ≥ 5, print ‘V’ and subtract 5.
  6. While n ≥ 1, print ‘I’ and subtract 1.
  7. When n becomes 0, all Roman symbols have been printed.
  8. Stop the program.
C Program

#include <stdio.h>

int main() {
    int n;

    printf("Enter number (1-50):\n");
    scanf("%d", &n);

    while (n >= 50) { printf("L"); n -= 50; }
    while (n >= 10) { printf("X"); n -= 10; }
    while (n >= 5)  { printf("V"); n -= 5; }
    while (n >= 1)  { printf("I"); n -= 1; }

    return 0;
}
  
Sample Output

Enter number (1-50):
28
XXVIII
  
Explanation

The program repeatedly subtracts the largest possible Roman value (50, 10, 5, or 1) from the number and prints the corresponding symbol. This greedy approach constructs the Roman numeral from largest symbols to smallest, ensuring a correct representation in the range 1–50 for the basic symbols L, X, V and I.

6. String Insertion Using Function


Problem Statement

Write a C program using functions to insert a sub-string into a given string.

Student-Friendly Algorithm
  1. Start the program.
  2. Declare a main string s and a substring sub.
  3. Read or initialize the main string and substring.
  4. Read the position pos where the substring should be inserted.
  5. In the function insert():
    • Copy the first pos characters of s to a temporary string.
    • Append the substring to the temporary string.
    • Append the remaining part of s from pos onwards.
    • Copy the result back into s.
  6. Display the modified main string.
  7. Stop the program.
C Program

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

void insert(char s[], char sub[], int pos) {
    char temp[100];

    strncpy(temp, s, pos);
    temp[pos] = '\0';

    strcat(temp, sub);
    strcat(temp, s + pos);

    strcpy(s, temp);
}

int main() {
    char s[100] = "HELLO";
    char sub[50] = "WORLD";
    int pos = 3;

    insert(s, sub, pos);
    printf("%s\n", s);

    return 0;
}
  
Sample Output

HELWORLDLO
  
Explanation

The function first copies the part of the original string before the insertion point into a temporary buffer. It then appends the substring and finally appends the remaining part of the original string, creating a new combined string which replaces the original.

7. Merge Two Files


Problem Statement

Write a C program to merge two files into a third file.

Student-Friendly Algorithm
  1. Start the program.
  2. Declare three file pointers for the two input files and the destination file.
  3. Open the first file (a.txt) in read mode.
  4. Open the second file (b.txt) in read mode.
  5. Open the third file (c.txt) in write mode.
  6. Copy all characters from the first file to the third file.
  7. Copy all characters from the second file to the third file.
  8. Close all three files.
  9. Stop the program.
C Program

#include <stdio.h>

int main() {
    FILE *f1, *f2, *f3;
    char ch;

    f1 = fopen("a.txt", "r");
    f2 = fopen("b.txt", "r");
    f3 = fopen("c.txt", "w");

    while ((ch = fgetc(f1)) != EOF) fputc(ch, f3);
    while ((ch = fgetc(f2)) != EOF) fputc(ch, f3);

    fclose(f1);
    fclose(f2);
    fclose(f3);

    return 0;
}
  
Sample Output

(After execution, file c.txt contains contents of a.txt followed by b.txt)
  
Explanation

The program reads each character from the first and then the second file using fgetc(), and writes it into the destination file using fputc(). This sequential copying merges both files into a single output file.

8. Reverse Array Using Pointer


Student-Friendly Algorithm
  1. Start the program.
  2. Declare and initialize an array with some integer values.
  3. Declare a pointer and make it point to the last element of the array.
  4. Use a loop to print the value pointed to by the pointer, then decrement the pointer to move backwards.
  5. Repeat until all elements have been printed in reverse order.
  6. Stop the program.
C Program

#include <stdio.h>

int main() {
    int a[5] = {1, 2, 3, 4, 5}, *p = &a[4];
    int i;

    for (i = 0; i < 5; i++) {
        printf("%d ", *p);
        p--;
    }

    return 0;
}
  
Sample Output

5 4 3 2 1
  
Explanation

The pointer is initialized to the address of the last array element. Each time the loop runs, the program prints the value at the current pointer location and then decrements the pointer to move to the previous element, effectively traversing the array backwards.

9. Sum of Array Using Pointer


Student-Friendly Algorithm
  1. Start the program.
  2. Declare and initialize an array with some integer values.
  3. Declare a pointer and set it to point to the first element of the array.
  4. Initialize sum = 0.
  5. Use a loop to add the value pointed to by the pointer to sum, then increment the pointer.
  6. After all elements are processed, display the sum.
  7. Stop the program.
C Program

#include <stdio.h>

int main() {
    int a[5] = {1, 2, 3, 4, 5}, sum = 0, *p = a;
    int i;

    for (i = 0; i < 5; i++) {
        sum += *p;
        p++;
    }

    printf("Sum = %d\n", sum);
    return 0;
}
  
Sample Output

Sum = 15
  
Explanation

The pointer p starts at the first element and moves forward one element at a time. Dereferencing *p gives the current element value, which is added to sum, illustrating how pointers can be used instead of array indices to access elements.

10. Insertion Sort (Ascending)


Student-Friendly Algorithm
  1. Start the program.
  2. Declare and initialize an array with unsorted integers.
  3. Consider the first element as already sorted.
  4. For each element from index 1 to the end:
    • Store the current value in key.
    • Shift all larger elements in the sorted portion one position to the right.
    • Insert key into the correct position to maintain ascending order.
  5. After the loop, the array is sorted in ascending order.
  6. Display the sorted array.
  7. Stop the program.
C Program

#include <stdio.h>

int main() {
    int a[5] = {5, 3, 1, 4, 2}, key, j;
    int i;

    for (i = 1; i < 5; i++) {
        key = a[i];
        j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }

    for (i = 0; i < 5; i++)
        printf("%d ", a[i]);

    return 0;
}
  
Sample Output

1 2 3 4 5
  
Explanation

The algorithm gradually builds a sorted section at the beginning of the array. For each new element, all larger elements in the sorted section are shifted one position to the right to make space, and the new element is inserted into its correct location, resulting in an ascending order arrangement.