Coding Questions Questions

Question Bank › Technical › C › Coding Questions

12

Other questions

Q101.Easy
Write a C program that reads an integer from the user and prints its digits in reverse order. For example, if the user enters 4726, the program should print 6274.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int num, reverse = 0, digit;
    printf("Enter a number to reverse: ");
    scanf("%d", &num);
    while (num != 0)
    {
        digit = num % 10;
        reverse = reverse * 10 + digit;
        num = num / 10;
    }
    printf("Reverse of entered number is = %d\n", reverse);
    return 0;
}
Explanation: 1) Initialise reverse = 0. 2) In each loop pass, get the last digit with num % 10. 3) Shift the current reverse left by one place (reverse * 10) and add the digit. 4) Remove the last digit from num using num / 10. 5) Repeat until num becomes 0, then print reverse. Example: 4726 -> 6, then 62, then 627, then 6274.
Q102.Easy
Write a C program that reads an integer and prints its digits in reverse order (for example, input 4729 should print 9274).
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int n, reverse = 0, rem;
    printf("Enter a number: ");
    scanf("%d", &n);
    while(n != 0)
    {
        rem = n % 10;
        reverse = reverse * 10 + rem;
        n /= 10;
    }
    printf("Reversed Number: %d", reverse);
    return 0;
}
Explanation: 1) Read the integer n and initialise reverse = 0. 2) In each loop iteration, rem = n % 10 extracts the last digit. 3) reverse = reverse * 10 + rem appends that digit to the reversed number. 4) n /= 10 removes the last digit from n. 5) Repeat until n becomes 0, then print reverse. Example: 4729 -> 9, then 92, then 927, then 9274.
Q103.Easy
Write a C program that swaps two integers entered by the user without using a third variable, and prints the values before and after swapping.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int x, y;
    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);
    printf("Before swap x=%d y=%d", x, y);
    x = x + y;
    y = x - y;
    x = x - y;
    printf("\nAfter swap x=%d y=%d", x, y);
    return 0;
}
Explanation: 1) Read two integers x and y from the user. 2) Print them before swapping. 3) Set x = x + y, so x now holds the sum. 4) Set y = x - y, which gives the original x. 5) Set x = x - y, which gives the original y. 6) Print x and y again; they are now swapped without any third variable.
Q104.Easy
Write a C program that prints "Jai Hind" without using any semicolon in the program, using an if statement.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
if(printf("Jai Hind"))
{
}
}
Explanation: 1. printf("Jai Hind") prints the text and returns 8 (number of characters), which is non-zero. 2. Since the condition is true, the empty if-block runs (does nothing). 3. The program contains no semicolons: the if condition ends with ')', the empty block uses braces, and return 0 is the last statement before the closing brace. 4. Output: Jai Hind
Q105.Easy
Write a C program that reads a positive integer and prints the sum of all its digits. For example, if the number is 4729, the output should be 22.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int num, r, s = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    while(num != 0)
    {
        r = num % 10;
        s = s + r;
        num = num / 10;
    }
    printf("The sum of the digits is : %d\n", s);
    return 0;
}
Explanation: 1. Read the integer num and initialise sum s = 0. 2. In a while loop that runs until num becomes 0, extract the last digit with r = num % 10. 3. Add that digit to s. 4. Remove the last digit with num = num / 10. 5. Repeat until num is 0, then print s. 6. Example: 4729 gives 9+2+7+4 = 22.
Q106.Easy
Write a C program that reads n integers into an array and prints the sum of the two smallest numbers in the array. For example, if the input array is 4 8 6 2 10, the two smallest numbers are 2 and 4, so the output should be 6.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a[50], n, i, j, temp, sum;
    printf("Enter array size: ");
    scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for(i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for(i = 0; i < n - 1; i++)
    {
        for(j = i + 1; j < n; j++)
        {
            if(a[i] > a[j])
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    sum = a[0] + a[1];
    printf("Sum of minimum two elements is : %d\n", sum);
    return 0;
}
Explanation: 1. Read the array size n and then n integers into array a. 2. Use a nested loop selection-style sort: for each i, compare a[i] with every later element a[j] and swap if a[i] > a[j], so the array becomes sorted in ascending order. 3. After sorting, the two smallest values are a[0] and a[1]. 4. Add them into sum and print the result. 5. Example: input 4 8 6 2 10 sorts to 2 4 6 8 10, so sum = 2 + 4 = 6.
Q107.Easy
Write a C program that reads two arrays of integers from the user and prints the union of the two arrays, i.e. all distinct elements appearing in either array, without duplicates. Print the elements of the first array first, then any elements of the second array that are not already present. For example, if the first array is 2 4 6 8 and the second array is 8 10 12, the output should be 2, 4, 6, 8, 10, 12.
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int a[20], b[20], n1, n2, i, j, found;

    printf("Enter size of first array: ");
    scanf("%d", &n1);
    printf("Enter elements of first array: ");
    for (i = 0; i < n1; i++)
        scanf("%d", &a[i]);

    printf("Enter size of second array: ");
    scanf("%d", &n2);
    printf("Enter elements of second array: ");
    for (i = 0; i < n2; i++)
        scanf("%d", &b[i]);

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

    for (i = 0; i < n2; i++)
    {
        found = 0;
        for (j = 0; j < n1; j++)
        {
            if (b[i] == a[j])
            {
                found = 1;
                break;
            }
        }
        if (!found)
            printf("%d, ", b[i]);
    }
    printf("\n");
    return 0;
}
Explanation: 1. Read the sizes and elements of the two arrays. 2. Print every element of the first array (these are all part of the union). 3. For each element of the second array, scan the first array to check whether it already appears there. 4. If it is not found in the first array, print it; otherwise skip it to avoid duplicates. 5. This produces the union of the two arrays with each distinct value printed once.
Q108.Easy
Write a C program that multiplies two non-negative integers WITHOUT using the multiplication operator (*). Read two integers from the user and print their product by repeated addition.
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int m, n, product = 0;
    printf("Enter two integers: ");
    scanf("%d %d", &m, &n);
    while (n > 0)
    {
        product = product + m;
        n--;
    }
    printf("Product is: %d\n", product);
    return 0;
}
Explanation: 1. Initialize product = 0. 2. The loop runs n times; each iteration adds m to product. 3. After n iterations, product = m + m + ... (n times) = m * n. 4. n is decremented each time until it reaches 0. 5. Finally the program prints the computed product.
Q109.Easy
Write a C program to print all perfect cube numbers up to 100 (i.e., 1, 8, 27, 64).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n = 1;
    while (n * n * n < 100)
    {
        printf("%4d ", n * n * n);
        n++;
    }
    return 0;
}
Explanation: 1. Start with n = 1. 2. In a while loop, check whether n*n*n is less than 100. 3. If yes, print n*n*n (the perfect cube) and increment n. 4. The loop stops when the cube reaches or exceeds 100. 5. Output: 1 8 27 64.
Q110.Medium
Write a C program that reads the order of two matrices (up to 10 x 10), reads the elements of both matrices, and then prints their sum matrix. The addition should be computed and printed directly (a[i][j] + b[i][j]) without storing the result in a third matrix.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, j, rows, cols, a[10][10], b[10][10];
    printf("Enter the order of matrix up to (10 x 10):\n");
    scanf("%d %d", &rows, &cols);
    printf("\nEnter the elements of matrix A:\n");
    for(i = 0; i < rows; i++)
        for(j = 0; j < cols; j++)
            scanf("%d", &a[i][j]);
    printf("\nEnter the elements of matrix B:\n");
    for(i = 0; i < rows; i++)
        for(j = 0; j < cols; j++)
            scanf("%d", &b[i][j]);
    printf("\nMatrix Addition:\n");
    for(i = 0; i < rows; i++)
    {
        for(j = 0; j < cols; j++)
            printf("%4d", a[i][j] + b[i][j]);
        printf("\n");
    }
    return 0;
}
Explanation: 1. Declare two 2D arrays a and b of size 10x10 and read the matrix order rows and cols. 2. Use a pair of nested for loops to read all elements of matrix A into a[i][j]. 3. Use another pair of nested for loops to read all elements of matrix B into b[i][j]. 4. A third pair of nested for loops prints a[i][j] + b[i][j] directly with %4d formatting, so no separate sum matrix is needed. 5. After each row, print a newline to format the output as a matrix.
Q111.Medium
Write a C program to print the following alphabet pattern using ASCII values (A = 65, B = 66, ...). The first line prints A, the second line prints B A, the third line prints C B A, and so on up to the line that prints E D C B A:
A
B A
C B A
D C B A
E D C B A
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int row, ch;
    for(row = 65; row <= 69; row++)
    {
        for(ch = row; ch >= 65; ch--)
        {
            printf("%c ", ch);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The outer for loop uses row from 65 (A) to 69 (E); each value of row is the last (largest) letter of that line. 2. The inner for loop starts ch at row and decreases down to 65, printing each character with %c followed by a space. 3. So line 1 (row=65) prints A; line 2 (row=66) prints B A; line 3 prints C B A, and so on. 4. After each inner loop, printf("\n") moves to the next line. 5. The result is the required 5-line alphabet pattern.
Q112.Medium
Write a C program that checks whether a given number is an Armstrong number. An Armstrong number (for 3-digit numbers) is one whose value equals the sum of the cubes of its digits. For example, 370 is an Armstrong number because 3³ + 7³ + 0³ = 27 + 343 + 0 = 370. Read an integer from the user and print whether it is an Armstrong number or not.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n, original, digit, sum = 0;
    printf("Enter a number : ");
    scanf("%d", &n);
    original = n;
    while (n > 0)
    {
        digit = n % 10;
        sum = sum + (digit * digit * digit);
        n = n / 10;
    }
    if (sum == original)
        printf("\n%d is an armstrong number", original);
    else
        printf("\n%d is not an armstrong number", original);
    return 0;
}
Explanation: 1) Read the number n and store a copy in 'original'. 2) Initialise sum = 0. 3) Loop while n > 0: take the last digit with n % 10, add its cube to sum, then remove the digit with n = n / 10. 4) After the loop, compare sum with original. 5) If equal, print that it is an Armstrong number; otherwise print that it is not. Example: for 370, cubes 27 + 343 + 0 = 370, so it prints '370 is an armstrong number'.
Q113.Medium
Write a C program that reads n integers from the user and prints them in ascending order.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, j, n, a[50], temp;
    printf("Enter how many numbers : ");
    scanf("%d", &n);
    printf("Enter %d numbers : ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (a[i] > a[j])
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    printf("----Ascending Order----\n");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    return 0;
}
Explanation: 1. Read the count n and then n integers into the array a. 2. Use two nested loops: for each position i, compare a[i] with every later element a[j]. 3. Whenever a[i] > a[j], swap them using a temporary variable temp. 4. After the loops the array is sorted in ascending order; print each element.
Q114.Medium
Write a C program that reads a limit n from the user, then reads n integers one by one, and finally prints the biggest of those n numbers. Use a loop to read the numbers and keep track of the largest value seen so far.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, limit, num, biggest;
    printf("Enter the limit : ");
    scanf("%d", &limit);
    printf("\nEnter %d numbers\n", limit);
    for(i = 0; i < limit; i++)
    {
        printf("\nEnter number %d : ", i + 1);
        scanf("%d", &num);
        if(i == 0 || num > biggest)
            biggest = num;
    }
    printf("The biggest number is %d", biggest);
    return 0;
}
Explanation: 1. Read the limit n into 'limit'. 2. Loop i from 0 to limit-1, reading each number into 'num'. 3. For the first number (i==0) store it as 'biggest'; for later numbers, replace 'biggest' only if the new number is larger. 4. After the loop, print 'biggest'. This correctly handles negative numbers too because the first value initialises 'biggest'.
Q115.Medium
Write a C program to check whether a number entered by the user is a palindrome or not. A palindrome number reads the same forwards and backwards. For example, 121, 1331, and 12321 are palindromes.
Show answer & explanation
Answer:
#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 number.\n", original);
    else
        printf("%d is not a palindrome number.\n", original);
    return 0;
}
Explanation: 1. Read an integer from the user. 2. Store the original number for later comparison. 3. Initialize a variable to build the reversed number. 4. While the number is not zero, extract the last digit, append it to the reversed number, and remove the last digit from the number. 5. After the loop, compare the reversed number with the original. 6. Print whether it is a palindrome or not.
Q116.MediumAnswer under review
Write a C program that demonstrates that once an identifier is declared with a data type, it cannot be redeclared with the same data type again. Declare an int variable named marks with value 72, then attempt to redeclare another variable named Marks (same name with different case) and also try to redeclare Marks as an int with value 88.5. Print both values using %d.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int marks = 72;
    int Marks;
    int Marks = 88.5;
    printf("The marks are %d ", marks);
    printf("\nThe Marks are %d ", Marks);
    return 0;
}
Explanation: Step 1: Include <stdio.h> for printf. Step 2: Declare int marks = 72 — a valid declaration. Step 3: Declare int Marks; — a separate identifier because C is case-sensitive. Step 4: int Marks = 88.5; redeclares Marks in the same scope, which is a compile-time error (redeclaration). Step 5: The program shows that an identifier cannot be redeclared with the same data type in the same scope; the case difference (marks vs Marks) makes them distinct identifiers.
Q117.Medium
Write a C program that reads a text file named "source.txt" character by character and writes its entire content twice (i.e., the content repeated back-to-back) into another file named "target.txt".
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    FILE *in, *out;
    int ch;

    in = fopen("source.txt", "r");
    if (in == NULL) {
        printf("Could not open source.txt\n");
        return 1;
    }
    out = fopen("target.txt", "w");
    if (out == NULL) {
        printf("Could not open target.txt\n");
        fclose(in);
        return 1;
    }

    while ((ch = fgetc(in)) != EOF) {
        fputc(ch, out);
    }

    rewind(in);

    while ((ch = fgetc(in)) != EOF) {
        fputc(ch, out);
    }

    fclose(in);
    fclose(out);
    printf("Content written twice to target.txt\n");
    return 0;
}
Explanation: 1. Open "source.txt" in read mode and "target.txt" in write mode; check both for NULL. 2. First pass: read each character with fgetc until EOF and write it with fputc to the output file. 3. Use rewind(in) to move the read pointer back to the start of the source file. 4. Second pass: repeat the read-write loop so the whole content is written a second time. 5. Close both files with fclose. The target file now contains the source content twice.
Q118.Medium
Write a C program that reads an integer stored in a file named "num.txt" and replaces the file's content with double that integer. For example, if the file contains 7, after running the program the file should contain 14.
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    FILE *fp;
    int n;

    fp = fopen("num.txt", "r");
    if (fp == NULL) {
        printf("Cannot open file\n");
        return 1;
    }
    fscanf(fp, "%d", &n);
    fclose(fp);

    n = n * 2;

    fp = fopen("num.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file\n");
        return 1;
    }
    fprintf(fp, "%d", n);
    fclose(fp);

    printf("New value: %d\n", n);
    return 0;
}
Explanation: 1. Open "num.txt" in read mode ("r") and check the pointer is not NULL. 2. Read the integer with fscanf(fp, "%d", &n). 3. Close the file with fclose(fp). 4. Double the value: n = n * 2. 5. Reopen the same file in write mode ("w"), which truncates the old content. 6. Write the new value with fprintf(fp, "%d", n) and close the file. 7. Example: file had 7, after doubling it holds 14.
Q119.Medium
In C, a student opens a file using fopen with mode "r" and later opens another file with mode "rb". Explain the difference between these two modes, and write a short C program that opens a file named "marks.txt" in "r" mode and a file named "photo.dat" in "rb" mode, printing an appropriate message for each based on whether fopen succeeds or fails.
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    FILE *textFile = fopen("marks.txt", "r");
    if (textFile == NULL) {
        printf("Could not open marks.txt in r mode\n");
    } else {
        printf("marks.txt opened in r mode (text read)\n");
        fclose(textFile);
    }

    FILE *binFile = fopen("photo.dat", "rb");
    if (binFile == NULL) {
        printf("Could not open photo.dat in rb mode\n");
    } else {
        printf("photo.dat opened in rb mode (binary read)\n");
        fclose(binFile);
    }
    return 0;
}
Explanation: 1. Mode "r" opens an existing file for reading as a text stream; on some systems newline characters may be translated (e.g. \r\n to \n). 2. Mode "rb" opens an existing file for reading as a binary stream; no such translation happens, so bytes are read exactly as stored. 3. Both modes fail (return NULL) if the file does not exist. 4. The program calls fopen twice, checks each result against NULL, prints a success or failure message, and closes any file that was opened successfully with fclose.
Q120.Medium
Write a C program to implement a simple Hangman game. The program should have a secret word (e.g., "india") and allow the user to guess letters one by one. It should display the current state of the word with dashes for unguessed letters. The user gets a limited number of wrong guesses (e.g., 5). The game ends when the word is guessed or the user runs out of attempts.
Show answer & explanation
Answer:
#include <stdio.h>
#include <string.h>

int main() {
    char word[] = "india";
    int len = strlen(word);
    char guessed[20];
    int i, attempts = 5, correct = 0;
    char ch;
    for (i = 0; i < len; i++)
        guessed[i] = '_';
    guessed[len] = '\0';
    printf("Welcome to Hangman!\n");
    printf("Guess the word: %s\n", guessed);
    while (attempts > 0 && correct < len) {
        printf("\nEnter a letter: ");
        scanf(" %c", &ch);
        int found = 0;
        for (i = 0; i < len; i++) {
            if (word[i] == ch && guessed[i] == '_') {
                guessed[i] = ch;
                correct++;
                found = 1;
            }
        }
        if (found)
            printf("Good guess!\n");
        else {
            attempts--;
            printf("Wrong guess! Attempts left: %d\n", attempts);
        }
        printf("Current word: %s\n", guessed);
    }
    if (correct == len)
        printf("\nCongratulations! You guessed the word: %s\n", word);
    else
        printf("\nSorry, you ran out of attempts. The word was: %s\n", word);
    return 0;
}
Explanation: 1. The secret word is stored in a character array. 2. An array 'guessed' is initialized with underscores to show unguessed letters. 3. The user is prompted to guess a letter. 4. If the letter is in the word and not already guessed, it is revealed and the correct count increases. 5. If the letter is not in the word, the number of attempts decreases. 6. The game continues until the word is fully guessed or attempts run out. 7. Finally, a win or lose message is displayed.
Q121.Medium
Write a C program to find the intersection of two arrays. The program should read the size and elements of two arrays and print the common elements (each common element printed once, in the order they appear in the first array).
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int a[100], b[100], n1, n2, i, j, k, found;
    printf("Enter size of first array: ");
    scanf("%d", &n1);
    printf("Enter elements of first array: ");
    for (i = 0; i < n1; i++)
        scanf("%d", &a[i]);
    printf("Enter size of second array: ");
    scanf("%d", &n2);
    printf("Enter elements of second array: ");
    for (i = 0; i < n2; i++)
        scanf("%d", &b[i]);
    printf("Intersection: ");
    for (i = 0; i < n1; i++) {
        found = 0;
        for (j = 0; j < n2; j++) {
            if (a[i] == b[j]) {
                found = 1;
                break;
            }
        }
        if (found) {
            // check if already printed
            int already = 0;
            for (k = 0; k < i; k++) {
                if (a[k] == a[i]) {
                    already = 1;
                    break;
                }
            }
            if (!already)
                printf("%d ", a[i]);
        }
    }
    printf("\n");
    return 0;
}
Explanation: 1. Read the sizes and elements of two arrays. 2. For each element in the first array, check if it exists in the second array. 3. If it exists, check if it has already been printed (to avoid duplicates). 4. If not printed before, print it. 5. This prints the intersection in the order of the first array.
Q122.Medium
Write a C program that reads two matrices from the user and prints their product. First read the order of matrix A (rows and columns), then its elements; then read the order of matrix B and its elements. If the number of columns of A is not equal to the number of rows of B, print 'Multiplication not possible' and stop. Otherwise print the product matrix, one row per line with elements separated by spaces.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a[10][10], b[10][10], prod[10][10];
    int r1, c1, r2, c2, i, j, k;
    printf("Enter order of matrix A: ");
    scanf("%d%d", &r1, &c1);
    printf("Enter elements of matrix A:\n");
    for(i = 0; i < r1; i++)
        for(j = 0; j < c1; j++)
            scanf("%d", &a[i][j]);
    printf("Enter order of matrix B: ");
    scanf("%d%d", &r2, &c2);
    if(c1 != r2)
    {
        printf("Multiplication not possible\n");
        return 0;
    }
    printf("Enter elements of matrix B:\n");
    for(i = 0; i < r2; i++)
        for(j = 0; j < c2; j++)
            scanf("%d", &b[i][j]);
    for(i = 0; i < r1; i++)
    {
        for(j = 0; j < c2; j++)
        {
            prod[i][j] = 0;
            for(k = 0; k < c1; k++)
                prod[i][j] += a[i][k] * b[k][j];
            printf("%d ", prod[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the order and elements of matrix A, then the order and elements of matrix B. 2) Check that columns of A (c1) equal rows of B (r2); if not, print the error message and exit. 3) For each cell (i,j) of the result, set prod[i][j] = 0 and add a[i][k]*b[k][j] for every k from 0 to c1-1. 4) Print each row of the product matrix followed by a newline.
Q123.Medium
Write a C program to print the following number pattern using nested for loops, where every leading blank position is shown as 0:

00001
00021
00321
04321
54321

Hint: use three for loops — the outer loop controls the lines, one inner loop prints the 0s, and another inner loop prints the descending numbers.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a, i, j;
    for(a = 1; a <= 5; a++)
    {
        for(i = 5; i > a; i--)
        {
            printf("0");
        }
        for(j = a; j >= 1; j--)
        {
            printf("%d", j);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Outer loop runs a from 1 to 5, giving 5 lines. 2) First inner loop prints 0 exactly (5-a) times (for a=1 prints four 0s; for a=5 prints none). 3) Second inner loop prints numbers from a down to 1 (for a=3 prints '321'). 4) Example a=2: first loop prints 000, second loop prints 21 → line '00021'. 5) A newline after each line gives the required pattern.
Q124.Medium
Write a C program to print the following number pattern using nested for loops:

55555
45555
34555
23455
12345

Hint: use three for loops — the outer loop controls the number of lines, one inner loop prints the leading numbers, and another inner loop prints the trailing 5s.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a, i, j;
    for(a = 5; a >= 1; a--)
    {
        for(i = a; i <= 5; i++)
        {
            printf("%d", i);
        }
        for(j = a - 1; j >= 1; j--)
        {
            printf("5");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Outer loop runs a from 5 down to 1, giving 5 lines. 2) First inner loop prints numbers from a up to 5 (for a=5 prints '5'; for a=1 prints '12345'). 3) Second inner loop prints the digit 5 exactly (a-1) times to fill the rest of the line. 4) Example a=3: first loop prints 3,4,5 and second loop prints 5,5 → line '34555'. 5) After each line a newline is printed, producing the required pattern.
Q125.Medium
Write a C program that reads a username and a password from the user, but masks the password with asterisks (*) as it is typed. The program should then display the entered password (for demonstration). Use getch() for character input without echo. Assume the maximum length for username and password is 20 characters.
Show answer & explanation
Answer:
#include <stdio.h>
#include <conio.h>

int main() {
    char username[21], password[21];
    int ch, i = 0;
    printf("Username: ");
    scanf("%20s", username);
    printf("Password: ");
    while (i < 20 && (ch = getch()) != '\r' && ch != '\n') {
        password[i++] = (char)ch;
        printf("*");
    }
    password[i] = '\0';
    printf("\nYour password is: %s\n", password);
    return 0;
}
Explanation: 1. Include stdio.h for standard I/O and conio.h for getch(). 2. Declare username and password arrays of size 21 (20 characters + null terminator), and a character variable ch. 3. Prompt for username and read it using gets() (unsafe but used here for simplicity). 4. Prompt for password. Use a while loop to read characters one by one with getch(), which does not echo. 5. For each character, if it is not carriage return ('\r') and the length is less than 20, store it in the password array and print an asterisk. 6. After the loop, null-terminate the password string. 7. Print the stored password to demonstrate that it was captured. 8. Return 0.
Q126.Medium
Write a C program that asks the user to enter a number and prints whether it is a perfect number or not. A perfect number equals the sum of its proper divisors (for example, 6 = 1+2+3 and 28 = 1+2+4+7+14).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int num, i, sum;
    printf("Enter a number: ");
    scanf("%d", &num);
    sum = 0;
    for (i = 1; i < num; i++)
    {
        if (num % i == 0)
        {
            sum = sum + i;
        }
    }
    if (sum == num)
    {
        printf("%d is a perfect number\n", num);
    }
    else
    {
        printf("%d is not a perfect number\n", num);
    }
    return 0;
}
Explanation: 1) Read the number num. 2) Set sum = 0 and loop i from 1 to num-1. 3) If i divides num exactly (num % i == 0), add i to sum. 4) After the loop, compare sum with num. 5) If equal, print 'is a perfect number'; otherwise print 'is not a perfect number'.
Q127.Medium
Write a C program to print "Namaste" without using a semicolon anywhere in the code.
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    if (printf("Namaste")) {}
}
Explanation: 1. The printf function returns the number of characters printed, which is positive (7 for "Namaste"). 2. In C, any non-zero value is considered true. 3. We use the if statement with printf as the condition: if(printf("Namaste")) {}. The printf executes and prints "Namaste", then returns 7, which is true, so the empty block {} is executed. 4. No semicolon is used after the if statement or inside the block. 5. The return 0; statement ends the program, but it contains a semicolon. However, the problem says "without using a semicolon" meaning we cannot use semicolons to terminate statements, but return 0; is necessary. To strictly avoid any semicolon, we can omit return 0; or use a different approach. But the common solution uses if(printf(...)){} and then return 0; which has a semicolon. To truly avoid semicolons, we can write the entire program without any semicolon by using the fact that the main function can be defined without a return type and the last statement can be an expression. For example: #include <stdio.h> int main() { if (printf("Namaste")) {} } This program has no semicolons at all. The if statement does not require a semicolon after the closing brace. So this is a valid C program that prints "Namaste" without any semicolon. 6. Therefore, the answer is the program shown.
Q128.Medium
Write a C program that adds two integers 15 and 25 using inline assembly code and prints the result.
Show answer & explanation
Answer:
#include<stdio.h>
int main() {
   int a = 15, b = 25, c;

   __asm__ __volatile__(
      "addl %%ebx, %%eax"
      : "=a"(c)
      : "a"(a), "b"(b)
   );

   printf("c= %d", c);
   return 0;
}
Explanation: 1. Variables a=15 and b=25 are declared; c will hold the sum. 2. The asm block uses registers: mov ax,a copies 15 into AX; mov bx,b copies 25 into BX. 3. add ax,bx computes AX = 15 + 25 = 40. 4. mov c,ax stores 40 into c. 5. printf prints 'c= 40'.
Q129.Medium
Write a C program that prints "Namaste" to the screen without defining a function named main(). Use a preprocessor macro to rename the entry function.
Show answer & explanation
Answer:
#include<stdio.h>
#define begin main
void begin() {
   printf("Namaste");
}
Explanation: 1. The preprocessor directive #define begin main makes the compiler replace every occurrence of 'begin' with 'main' before compilation. 2. So the function void begin() becomes void main(), which is the required entry point. 3. Inside it, printf("Namaste") prints the text. 4. Thus the program runs without the programmer literally typing main().
Q130.Medium
Write a C program that reads the order of two square matrices (number of rows and columns), reads both matrices from the user, and prints their matrix product. For example, multiplying [[1,2],[3,4]] by [[5,6],[7,8]] should print 19 22 on the first row and 43 50 on the second row.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int a[10][10], b[10][10], prod[10][10], r, c, i, j, k;
    printf("Enter the number of rows = ");
    scanf("%d", &r);
    printf("Enter the number of columns = ");
    scanf("%d", &c);
    printf("Enter the elements of the first matrix:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &a[i][j]);
    printf("Enter the elements of the second matrix:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &b[i][j]);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            prod[i][j] = 0;
            for (k = 0; k < c; k++)
                prod[i][j] += a[i][k] * b[k][j];
        }
    }
    printf("Product of the matrices =\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++)
            printf("%d\t", prod[i][j]);
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the order r x c and the elements of both matrices a and b. 2) For each cell prod[i][j], initialise it to 0. 3) Add a[i][k] * b[k][j] for every k from 0 to c-1: this is the row-by-column dot product. 4) Print the resulting matrix row by row. 5) Check: [[1,2],[3,4]] x [[5,6],[7,8]] gives prod[0][0]=1*5+2*7=19, prod[0][1]=1*6+2*8=22, prod[1][0]=3*5+4*7=43, prod[1][1]=3*6+4*8=50.
Q131.Medium
Write a C program that reads a limit n from the user and prints a Fibonacci triangle with n rows. Row 1 starts with 1; each following row starts again from 1 and contains one more Fibonacci number than the previous row. For n = 4 the output should be:
1
1 1
1 1 2
1 1 2 3
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int a, b, c, i, j, n;
    printf("Enter the limit: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++) {
        a = 0;
        b = 1;
        printf("%d\t", b);
        for (j = 1; j < i; j++) {
            c = a + b;
            printf("%d\t", c);
            a = b;
            b = c;
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Read the number of rows n. 2. Outer loop i runs from 1 to n, one iteration per row. 3. At the start of each row reset a = 0 and b = 1, then print the first Fibonacci number b (= 1). 4. Inner loop runs i-1 times: compute c = a + b, print it, then shift a = b and b = c to get the next Fibonacci number. 5. So row i contains i Fibonacci numbers, each row starting fresh from 1, giving the triangle shape. 6. After the inner loop, print a newline to move to the next row.
Q132.Medium
Write a C program that reads a positive integer entered by the user and prints each of its digits as an English word, in the same order as the digits appear. For example, if the user enters 4072, the program should print: four zero seven two
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    long int num;
    int digits[20], n = 0, i;
    const char *words[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    printf("Enter the number: ");
    scanf("%ld", &num);

    if (num == 0) {
        digits[n++] = 0;
    }
    while (num > 0) {
        digits[n++] = num % 10;
        num = num / 10;
    }
    for (i = n - 1; i >= 0; i--) {
        printf("%s ", words[digits[i]]);
    }
    printf("\n");
    return 0;
}
Explanation: 1. Read the integer num from the user. 2. First while loop: repeatedly take the last digit (num % 10) and build a reversed number rev = rev*10 + digit, then drop the last digit (num = num/10). This reverses the digit order. 3. Second while loop: take each digit of rev (rev % 10) and use a switch statement to print the matching English word (zero, one, ... nine). 4. Divide rev by 10 each time so the next digit is processed. 5. Because the number was reversed first, the words are printed in the original left-to-right order of the digits.
Q133.Medium
Write a C program that reads an integer n and prints an X-shaped star pattern of size (2n-1) rows and (2n-1) columns. Stars are printed where the row index equals the column index or where the column index equals (2n - row index). For example, if n = 3 the output is a 5x5 X made of stars.
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    int n, m;
    printf("Enter the number: ");
    scanf("%d", &n);
    m = 2 * n - 1;
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= m; j++) {
            if (i == j || j == (m - i + 1)) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n and set m = 2*n - 1, the side length of the square grid. 2) Use an outer loop i from 1 to m for rows and an inner loop j from 1 to m for columns. 3) Print a star when i == j (main diagonal) or when j == m - i + 1 (anti-diagonal). 4) Otherwise print a space so the X shape appears. 5) Print a newline after each row; for n = 3, m = 5 and the diagonals of a 5x5 grid form the X.
Q134.Medium
Write a C program that reads a string from the user and sorts its characters in alphabetical order (case-insensitive). For example, if the input is "Mumbai", the output should be "abimMu"? Actually, the sorting should be case-insensitive, so 'M' and 'm' are considered the same letter, but the original case is preserved in the output. For input "Mumbai", the sorted characters alphabetically (case-insensitive) would be: a, b, i, M, m, u? Wait, let's sort: letters: M, u, m, b, a, i. Case-insensitive order: a, b, i, M, m, u. But 'M' and 'm' are the same letter, so their relative order? Typically, we sort by the letter ignoring case, and if same letter, we can keep original order or sort by case. The original program used a loop from 'A' to 'Z' and checked both cases, so it would output all 'a's and 'A's first (in the order they appear in the string), then 'b's and 'B's, etc. So for "Mumbai", the output would be: a, b, i, M, m, u? Let's trace: i=65 ('A'): check each char: M (toupper=77) no, u (85) no, m (77) no, b (66) no, a (65) yes -> store 'a'; i (105) no. So store 'a'. i=66 ('B'): check: M no, u no, m no, b (66) yes -> store 'b'; a no; i no. store 'b'. i=67 ('C'): none. ... i=73 ('I'): check: M no, u no, m no, b no, a no, i (105) toupper=73 yes -> store 'i'. i=77 ('M'): check: M (77) yes -> store 'M'; u no; m (77) yes -> store 'm'; b no; a no; i no. So store 'M' then 'm'. i=85 ('U'): check: M no; u (85) yes -> store 'u'; m no; b no; a no; i no. So final store: a, b, i, M, m, u. That is "abimMu"? Actually concatenated: a b i M m u -> "abiMmu". But the original sample output was for a different input? The original sample output was 'aelpp' for some input? Not sure. For our example, output should be "abiMmu". But the question asks to write a program, not to compute output. So we need to provide a complete C program that does this sorting. We'll write a program that reads a string, sorts its characters in alphabetical order (case-insensitive), and prints the sorted string. We'll use the same logic as the original: iterate over 'A' to 'Z', and for each letter, scan the string and collect all characters that match that letter in either case, preserving their original order. Then print the collected characters.
Show answer & explanation
Answer:
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main()
{
    char text[100], sorted[100];
    int i, j, len, k = 0;

    printf("Enter a string: ");
    fgets(text, sizeof(text), stdin);
    text[strcspn(text, "\n")] = '\0';  // remove newline

    len = strlen(text);

    for (i = 'A'; i <= 'Z'; i++)
    {
        for (j = 0; j < len; j++)
        {
            if (toupper(text[j]) == i)
            {
                sorted[k++] = text[j];
            }
        }
    }
    sorted[k] = '\0';

    printf("Sorted characters alphabetically: %s\n", sorted);
    return 0;
}
Explanation: 1. The program reads a string using fgets and removes the trailing newline. 2. It initializes an empty array sorted to store the result. 3. It loops over each uppercase letter from 'A' to 'Z'. 4. For each letter, it scans the original string and checks if the uppercase version of the current character matches the letter. 5. If it matches, the original character (preserving case) is appended to sorted. 6. After processing all letters, the sorted string is null-terminated and printed. This method groups all characters by their letter, ignoring case, and within each letter group, the original order is preserved.
Q135.Medium
Write a C program that prints "Namaste India" to the console without using any semicolon in the source code. Use an if statement as part of the trick.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    if (printf("Namaste India"))
    {
    }
}
Explanation: 1. The printf function returns the number of characters printed, which is non-zero (13 for "Namaste India"). 2. In C, an if statement evaluates its condition; here the condition is the printf call, which executes and prints the string. 3. Since the return value is non-zero, the if condition is true, but the body is empty. 4. The return 0; statement ends the program, but note that it also lacks a semicolon? Actually, return 0; has a semicolon. To avoid semicolons entirely, we can omit the return statement or use a different approach. However, the original code used return 0; with a semicolon, which violates the 'without semicolon' rule. To truly avoid semicolons, we can write the program without any semicolons by using the if trick and omitting the return statement (C99 allows implicit return 0 in main). Alternatively, we can use a semicolon-free approach by placing the printf inside the if condition and using empty blocks. The provided answer includes return 0; with a semicolon, which is incorrect for the requirement. Let's correct it: The program should not contain any semicolon. Here is a corrected version: #include <stdio.h> int main() { if (printf("Namaste India")) { } } This program has no semicolons. The if condition calls printf, which prints the string and returns a non-zero value, so the empty block is executed. The main function ends without a return statement, which is allowed in C99 and later.
Q136.Medium
Write a C program that prints "Namaste India" without using any semicolon in the program, using a while loop.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
while(!printf("Namaste India"))
{
}
}
Explanation: 1. printf returns the number of characters printed (13 for "Namaste India"), which is non-zero, so the while condition is true. 2. The loop body executes once and hits break, so the loop ends after one print. 3. No semicolon is used anywhere: the while condition ends with ')', the break and return statements are written without ';' by placing them inside braces as the last statement (the closing brace acts as terminator). 4. Output: Namaste India
Q137.Medium
Write a C program that prints "Jai Hind" without using any semicolon in the source code. Use a while loop with a negated condition to achieve this.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    while(!printf("Jai Hind"))
    {
    }
}
Explanation: 1. The printf function prints "Jai Hind" and returns the number of characters printed (8). 2. The ! operator negates this return value: !8 is 0 (false). 3. The while loop condition is false, so the loop body (empty) is not executed. 4. No semicolons are used: the while statement and empty block require none. 5. The program prints the string once and exits.
Q138.Medium
Write a C program that prints "Namaste India" without using any semicolon in the source code. Use a switch statement to achieve this.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    switch(printf("Namaste India"))
    {
    }
}
Explanation: 1. The printf function prints "Namaste India" and returns the number of characters printed (13). 2. That return value is used as the controlling expression of the switch statement. 3. The switch body is empty, so no case matches, but the printf already executed. 4. No semicolons are used anywhere in the code (the switch statement and empty block require none). 5. The program compiles and runs, printing the desired string.
Q139.Medium
Write a C program that reads two integers from the user and prints their sum WITHOUT using the + operator. Use bitwise operations: the XOR of the two numbers gives the sum without carries, and the AND shifted left by one gives the carry, which is added repeatedly until the carry becomes zero. For example, if the user enters 4 and 7, the output should be: Addition of two numbers is : 11
Show answer & explanation
Answer:
#include <stdio.h>
int add(int, int);
int main()
{
    int num1, num2;
    printf("Enter any two integers : ");
    scanf("%d%d", &num1, &num2);
    printf("Addition of two numbers is : %d", add(num1, num2));
    return 0;
}
int add(int num1, int num2)
{
    if (!num2)
        return num1;
    else
        return add((num1 & num2) << 1, num1 ^ num2);
}
Explanation: 1) XOR (num1 ^ num2) adds the bits without carrying. 2) AND (num1 & num2) marks the positions where a carry is generated; shifting it left by 1 places the carry in the correct column. 3) Recursively call add with the new carry and the XOR result. 4) When the carry (second argument) becomes 0, the first argument is the final sum. 5) Example: 4 (100) and 7 (111): XOR = 011 = 3, AND<<1 = 1000 = 8; then 3 and 8: XOR = 1011 = 11, AND = 0, so answer 11.
Q140.Medium
Write a C program that reads the order (rows and columns) of a matrix from the user, reads all its elements, and prints the transpose of that matrix. For example, if the user enters a 2 x 3 matrix with elements 1 2 3 / 4 5 6, the program should print the 3 x 2 transpose: 1 4 / 2 5 / 3 6.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, j, rows, cols, a[10][10], t[10][10];
    printf("Enter the order of the matrix (rows cols, up to 10 x 10):\n");
    scanf("%d %d", &rows, &cols);
    printf("Enter the elements of the matrix:\n");
    for (i = 0; i < rows; i++)
        for (j = 0; j < cols; j++)
            scanf("%d", &a[i][j]);
    for (i = 0; i < rows; i++)
        for (j = 0; j < cols; j++)
            t[j][i] = a[i][j];
    printf("The transpose of the matrix is:\n");
    for (i = 0; i < cols; i++)
    {
        for (j = 0; j < rows; j++)
            printf("%4d", t[i][j]);
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the number of rows and columns of matrix a. 2) Read all elements into a[rows][cols]. 3) The transpose has order cols x rows, so store t[j][i] = a[i][j] for every element. 4) Print t row by row: outer loop runs cols times, inner loop runs rows times. 5) This turns each row of the original into a column of the result.
Q141.Medium
Write a C program that divides two positive integers without using the division operator (/) or the modulus operator (%). Read two integers from the user and print the integer quotient. For example, if the user enters 18 and 7, the program should print 2.
Show answer & explanation
Answer:
#include <stdio.h>

int divideWithoutOperator(int dividend, int divisor)
{
    int quotient = 0;
    int temp = 1;
    while (divisor <= dividend)
    {
        divisor <<= 1;
        temp <<= 1;
    }
    while (temp > 1)
    {
        divisor >>= 1;
        temp >>= 1;
        if (dividend >= divisor)
        {
            dividend -= divisor;
            quotient += temp;
        }
    }
    return quotient;
}

int main()
{
    int a, b;
    printf("Enter two positive integers: ");
    scanf("%d %d", &a, &b);
    printf("Quotient is: %d\n", divideWithoutOperator(a, b));
    return 0;
}
Explanation: 1. Read the dividend and divisor from the user. 2. Repeatedly left-shift the divisor and a multiplier 'temp' (starting at 1) until the divisor exceeds the dividend; this finds the largest power-of-two multiple. 3. Then shift back down: at each step halve divisor and temp; if the current dividend is at least the divisor, subtract it and add temp to the quotient. 4. The accumulated quotient is the integer division result, computed using only shifts, subtraction and comparison (no / or %). 5. Example: 18 and 7 -> divisor becomes 28 (temp 4), then back down: 14 fits (quotient 2, remainder 4), 7 does not fit -> quotient 2.
Q142.Medium
Write a C program that subtracts one integer from another WITHOUT using the subtraction operator (-). Read two integers from the user and print their difference (first minus second) using bitwise operations.
Show answer & explanation
Answer:
#include <stdio.h>

int subtract(int a, int b)
{
    int borrow;
    while (b != 0)
    {
        borrow = (~a) & b;
        a = a ^ b;
        b = borrow << 1;
    }
    return a;
}

int main()
{
    int x, y;
    printf("Enter two integers: ");
    scanf("%d %d", &x, &y);
    printf("Difference is: %d\n", subtract(x, y));
    return 0;
}
Explanation: 1. The function subtract(a, b) computes a - b using only bitwise operators. 2. borrow = (~a) & b finds the bits where a borrow is needed. 3. a = a ^ b performs the partial subtraction (like XOR in addition). 4. b = borrow << 1 shifts the borrow to the next higher bit. 5. The loop repeats until b becomes 0; then a holds the final difference. 6. main reads two integers and prints the result of subtract(x, y).
12

Get In Touch

INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India

contact@intmatedtech.com

TestMyIndia All India Rank