Coding Questions Questions

Question Bank › Technical › C › Coding Questions

12

Conditional Statements

Q1.Easy
Write a C program that reads two integers from the user and prints the bigger of the two.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a, b;
    printf("Enter first number : ");
    scanf("%d", &a);
    printf("Enter second number : ");
    scanf("%d", &b);
    if (a > b)
        printf("Bigger number : %d\n", a);
    else
        printf("Bigger number : %d\n", b);
    return 0;
}
Explanation: 1. Declare two integer variables a and b. 2. Read the first number into a and the second into b using scanf. 3. Compare a and b with an if-else: if a > b print a, otherwise print b. 4. The program ends with return 0.
Q2.Easy
What is the output of the following C program?

```c
int x = 5;
if (x == 5)
    printf("x is five");
else
    printf("x is not five");
```
  1. x is five
  2. x is not five
  3. No output
  4. Compilation error
Show answer & explanation
Answer: (A) x is five
Explanation: 1. The variable x is initialized to 5. 2. The condition (x == 5) evaluates to true. 3. Therefore, the printf statement inside the if block is executed, printing 'x is five'. 4. The else block is skipped.
Q3.Easy
Write a C program that asks the user to enter an integer and prints whether it is a positive number or a negative number. (Treat 0 as positive, as in the original.)
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int value;
    printf("Enter an integer: ");
    scanf("%d", &value);
    if (value >= 0)
    {
        printf("%d is a positive number\n", value);
    }
    else
    {
        printf("%d is a negative number\n", value);
    }
    return 0;
}
Explanation: 1) Declare an int variable value. 2) Read the integer from the user with scanf. 3) Use if (value >= 0) to check for zero or positive; print 'is a positive number'. 4) Otherwise (else) print 'is a negative number'. 5) Return 0 to end main.
Q4.Easy
Write a C program that reads two integers from the user and prints the smaller of the two. For example, if the user enters 18 and 7, the program should print the smallest number as 7.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a, b;
    printf("Enter first number : ");
    scanf("%d", &a);
    printf("Enter second number : ");
    scanf("%d", &b);
    if (a < b)
        printf("Smallest number : %d\n", a);
    else
        printf("Smallest number : %d\n", b);
    return 0;
}
Explanation: 1) Declare two integers a and b. 2) Read both values using scanf. 3) Compare a and b with an if condition (a < b). 4) If a is smaller, print a; otherwise print b. 5) The ternary form a < b ? a : b gives the same result.

Escape Sequences

Q5.Easy
Write a C program that prints the word "Delhi" and then, using the \n escape sequence, prints the word "Mumbai" on the next line.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("Delhi\nMumbai");
    return 0;
}
Explanation: Step 1: Include <stdio.h> for printf. Step 2: In main(), call printf with "Delhi\nMumbai". Step 3: The \n escape sequence (ASCII 010) moves the cursor to a new line, so 'Delhi' prints on the first line and 'Mumbai' on the second line. Step 4: return 0 finishes main successfully.
Q6.Easy
Write a C program that prints the word "Namaste" followed by a horizontal tab (using the \t escape sequence) and then the word "Bharat", all on a single line.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("Namaste\tBharat");
    return 0;
}
Explanation: Step 1: Include <stdio.h> so that printf is available. Step 2: In main(), call printf with the string "Namaste\tBharat". Step 3: The \t escape sequence inserts a horizontal tab between the two words, so output is 'Namaste' then a tab then 'Bharat' on one line. Step 4: return 0 ends the program successfully.
Q7.Easy
Write a C program that demonstrates the \b (backspace) escape sequence. The program should print "Hello\b Programmer " using a single printf statement and return 0 from main.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("Hello\b Programmer ");
    return 0;
}
Explanation: Step 1: Include <stdio.h> for printf. Step 2: printf("Hello\b Programmer ") prints 'Hello', then the \b backspace moves the cursor one position back over the 'o'. Step 3: The following space overwrites that 'o', so the visible output becomes 'Hell Programmer '. Step 4: main returns 0 to end the program successfully.
Q8.Easy
Write a C program that prints 'This is a beep' followed by a bell sound using the \a escape sequence. The output should be: This is a beep (and then the bell sound).
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    printf("This is a beep\a");
    return 0;
}
Explanation: 1. Include the standard I/O header for printf. 2. In the printf statement, write the text "This is a beep" followed by \a, which produces an alert (bell) sound. 3. The program outputs the text and then the bell sound.
Q9.Easy
Write a C program that prints the text 'Hello Coder' enclosed in single quotes using escape sequences. The output should be exactly: 'Hello Coder' (including the single quotes).
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    printf("\'Hello Coder\'");
    return 0;
}
Explanation: 1. Include the standard I/O header for printf. 2. In the printf statement, use \' to print a single quote, then the text Hello Coder, then another \' for the closing single quote. 3. The program outputs: 'Hello Coder'.
Q10.Easy
Write a C program that prints the following line exactly, including the double quotes around the greeting:

"Namaste Coder"

Note: the escape sequence \" prints a double quote character.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("\"Namaste Coder\"\n");
    return 0;
}
Explanation: 1. A double quote inside a string literal would normally end the string, so it must be escaped as \". 2. The output needs a quote before Namaste and after Coder, so use \" at both places. 3. Write printf("\"Namaste Coder\"\n"); — the \" pairs print the quotes and \n ends the line. 4. Include <stdio.h> for printf and return 0 from main.
Q11.Easy
Write a C program that prints the following line exactly, using escape sequences for the backslash characters:

C\practice\code\daily.in

Note: the escape sequence \\ prints a single backslash.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("C\\practice\\code\\daily.in\n");
    return 0;
}
Explanation: 1. In C, a backslash starts an escape sequence, so to print a literal backslash you must write \\. 2. The required output has three backslashes, so the format string needs three \\ pairs. 3. Write printf("C\\practice\\code\\daily.in\n"); — each \\ prints one backslash and \n ends the line. 4. Include <stdio.h> for printf and return 0 from main.
Q12.Easy
Write a C program that prints the text: \f - form feed sign.  (i.e. it should output a backslash character followed by the letter f, then the rest of the sentence).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("\\f - form feed sign. \n");
    return 0;
}
Explanation: 1. Include <stdio.h> for printf. 2. In the string, \\ is an escape sequence that prints a single backslash character. 3. The next character f is printed normally, so the output begins with \f. 4. The rest ' - form feed sign. ' is printed as plain text and \n moves to a new line. 5. return 0 ends the program.
Q13.Easy
Write a C program that uses the vertical tab escape sequence (\v) inside a printf statement to print the text "\v - vertical tab demo. " and then returns 0 from main.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("\v - vertical tab demo. ");
    return 0;
}
Explanation: 1. Include <stdio.h> for printf. 2. Define int main(). 3. Call printf with the string "\v - vertical tab demo. "; the \v escape sequence inserts a vertical tab character. 4. The vertical tab moves the cursor down to the next vertical tab stop before printing the remaining text. 5. return 0; exits main successfully.
Q14.Easy
Write a C program that prints the text "Namaste" followed by a null character escape sequence (\0) and then the word "Bharat", all using a single printf statement. The program should return 0 from main.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("Namaste \0 Bharat");
    return 0;
}
Explanation: 1. Include <stdio.h> so that printf is available. 2. Start main with int return type. 3. Use printf with the string "Namaste \0 Bharat"; the \0 is the null character escape sequence. 4. Because \0 is a null character, output stops being displayed at that point (the rest may not show), demonstrating the \0 escape. 5. return 0; ends the program successfully.
Q15.Medium
Write a C program that demonstrates the \r (carriage return) escape sequence. The program should print "\nab" first, then print "\bsi", and finally print "\rha". Use printf statements and return 0 from main.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    printf("\nab");
    printf("\bsi");
    printf("\rha");
    return 0;
}
Explanation: Step 1: Include <stdio.h> so printf is available. Step 2: printf("\nab") moves to a new line and prints 'ab'. Step 3: printf("\bsi") applies a backspace (\b) which erases the 'b', then prints 'si', so the line shows 'asi'. Step 4: printf("\rha") uses carriage return (\r) to move the cursor to the start of the line, then prints 'ha', overwriting the first two characters. Step 5: main returns 0 to signal successful execution.

File Handling

Q16.Easy
Write a C program that opens a text file named "nums.txt" containing three integers separated by spaces, reads the three integers from it, and prints them on the screen. If the file cannot be opened, print an error message.
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    int a, b, c;
    FILE *fp;

    fp = fopen("nums.txt", "r");
    if (fp == NULL) {
        printf("Error: could not open nums.txt\n");
        return 1;
    }

    if (fscanf(fp, "%d %d %d", &a, &b, &c) != 3) {
        printf("Error: file does not contain three integers\n");
        fclose(fp);
        return 1;
    }

    printf("The three integers are: %d, %d, %d\n", a, b, c);
    fclose(fp);
    return 0;
}
Explanation: 1. Open "nums.txt" in read mode ("r") and check the returned pointer for NULL. 2. Use fscanf with the format "%d %d %d" to read three integers into a, b and c; verify it returns 3. 3. Print the three values with printf. 4. Close the file with fclose to release the resource.
Q17.Easy
Write a C program that asks the user for a number and writes its multiplication table (from 1 to 10) in the text format "n x i = result", one line per entry, into a file named "table.txt". The file must be created/overwritten and properly closed so it is readable and well formatted.
Show answer & explanation
Answer:
#include <stdio.h>

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

    printf("Enter a number: ");
    if (scanf("%d", &n) != 1) {
        printf("Invalid input\n");
        return 1;
    }

    fp = fopen("table.txt", "w");
    if (fp == NULL) {
        printf("Could not open file\n");
        return 1;
    }

    for (i = 1; i <= 10; i++) {
        fprintf(fp, "%d x %d = %d\n", n, i, n * i);
    }

    fclose(fp);
    printf("Table written to table.txt\n");
    return 0;
}
Explanation: 1. Read the number n from the user with scanf. 2. Open "table.txt" in write mode ("w") so any old content is replaced; check fopen did not return NULL. 3. Loop i from 1 to 10 and use fprintf to write each line as "n x i = n*i" followed by \n, keeping the file well formatted. 4. Close the file with fclose so all data is flushed to disk and the file is readable.
Q18.Easy
Write a C program that attempts to open a file named "data.txt" for reading. Before opening, check if the file exists. If it does not exist, print "File not found". If it exists, open it and print "File opened successfully". Finally, close the file if it was opened.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    if ((fp = fopen("data.txt", "r")) == NULL) {
        printf("File not found\n");
    } else {
        printf("File opened successfully\n");
        fclose(fp);
    }
    return 0;
}
Explanation: 1. Include stdio.h for file operations and printf. 2. Declare a FILE pointer fp. 3. Use fopen("data.txt", "r") to try opening the file for reading. 4. If fopen returns NULL, the file does not exist or cannot be opened; print "File not found". 5. Otherwise, print "File opened successfully" and close the file with fclose(fp). 6. Return 0 to indicate successful execution.

Nested Loops and Number Patterns

Q19.Easy
Write a C program that prints the following number pattern using nested loops: the first line shows 1 2 3 4, the second line shows 1 2 3, the third line shows 1 2, and the last line shows 1. Each number should be printed without spaces between them (i.e. 1234, 123, 12, 1).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int row, col;
    for(row = 4; row >= 1; row--)
    {
        for(col = 1; col <= row; col++)
        {
            printf("%d", col);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) The outer loop runs row from 4 down to 1, giving 4 lines. 2) For each row, the inner loop prints col from 1 up to row. 3) Row 4 prints 1234, row 3 prints 123, row 2 prints 12, row 1 prints 1. 4) After each row a newline is printed, producing the required pattern.
Q20.Easy
Write a C program that prints the following pattern using nested for loops. The first (outer) loop decides how many lines to print; the second (inner) loop prints consecutive natural numbers starting from 1, continuing across lines. Print each number followed by a space and start a new line after each row. The output should be:
1 
2 3 
4 5 6 
7 8 9 10 
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a, i, k = 1;
    for(a = 1; a < 5; a++)
    {
        for(i = 1; i <= a; i++)
        {
            printf("%d ", k++);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) k is initialised to 1 and holds the next number to print. 2) The outer loop runs a = 1 to 4, giving 4 lines. 3) For each line a, the inner loop runs i = 1 to a, so line a has a numbers. 4) Each time we print k and then increment it with k++, so numbers continue across lines: 1 | 2 3 | 4 5 6 | 7 8 9 10. 5) A newline after each row gives the triangular pattern.
Q21.Easy
Write a C program that prints the following pattern using nested for loops. The first (outer) loop decides how many lines to print; the second (inner) loop prints the digits on each line. For line number a (starting from 1), print the digits 1 to a, but print 1 when the digit is odd and 0 when the digit is even, each followed by a space. So the output should be:
1 
0 1 
1 0 1 
0 1 0 1 
1 0 1 0 1 
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a, i;
    for(a = 1; a <= 5; a++)
    {
        for(i = 1; i <= a; i++)
        {
            printf("%d ", (a - i + 1) % 2);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) The outer loop runs a from 1 to 5, giving 5 lines. 2) For each line a, the inner loop runs i from 1 to a, so line a has a digits. 3) i % 2 gives 1 for odd i and 0 for even i, so we print 1,0,1,0,... 4) A space after each digit and a newline after each line produce the required pattern.

Pattern Printing

Q22.Easy
Write a C program that prints the following alphabet pattern using nested loops:

A
A B
A B C
A B C D
A B C D E

Each row starts from 'A' and continues up to the letter matching the row number (row 1 ends at 'A', row 2 ends at 'B', and so on).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int row, ch;
    for(row = 65; row <= 69; row++)
    {
        for(ch = 65; ch <= row; ch++)
        {
            printf("%c ", ch);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The outer loop runs row from 65 ('A') to 69 ('E'), controlling how many rows are printed (5 rows). 2. For each row, the inner loop runs ch from 65 ('A') up to the current row value, so row 1 prints 1 letter, row 2 prints 2 letters, etc. 3. printf("%c ", ch) prints each character followed by a space. 4. After the inner loop finishes, printf("\n") moves to the next line. 5. Output: A / A B / A B C / A B C D / A B C D E.
Q23.Easy
Write a C program to print the following number pattern:
54321
4321
321
21
1
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    for (int i = 5; i >= 1; i--) {
        for (int j = i; j >= 1; j--) {
            printf("%d", j);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The pattern has 5 lines. On line i (starting from 5 down to 1), we print numbers from i down to 1. 2. Use an outer loop with i from 5 down to 1. 3. Inside, an inner loop with j from i down to 1 prints each number. 4. After each line, print a newline. 5. This produces the required pattern.
Q24.Easy
Write a C program to print a square pattern of stars. The program should read an integer n from the user and print an n x n square of asterisks (*). For example, if n = 4, the output should be:
****
****
****
****
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, j;
    printf("Enter the size of the square: ");
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Include the standard I/O library. 2. Declare integer variables n (size), i and j (loop counters). 3. Prompt the user to enter the size and read it into n. 4. Use an outer loop (i from 0 to n-1) for each row. 5. Inside, use an inner loop (j from 0 to n-1) to print n asterisks in that row. 6. After the inner loop, print a newline to move to the next row. 7. Return 0 to indicate successful execution.
Q25.Easy
Write a C program that prints a mirror half diamond star pattern (Part 1) with 5 rows. The first row has 4 leading spaces followed by 1 star, and each following row has one fewer leading space and one more star, so the stars are right-aligned and increasing. The expected output is:
    *
   **
  ***
 ****
*****
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
int i, j, k;
for(i = 1;i <= 5;i++)
{
for(j = 5;j > i;j--)
{
printf(" ");
}
for(k = 1;k <= i;k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Explanation: 1) The outer loop i runs from 1 to 5, one iteration per row. 2) The first inner loop prints (5-i) leading spaces, so row 1 has 4 spaces, row 2 has 3, down to row 5 with 0. 3) The second inner loop prints i stars, giving 1,2,3,4,5 stars per row. 4) A newline after each row produces the right-aligned increasing star pattern.
Q26.Easy
Write a C program that prints a mirror half diamond star pattern (Part 2) with 4 rows. The first row has 4 stars, and each following row has one fewer star, with the stars right-aligned (leading spaces increase by one each row). The expected output is:
****
 ***
  **
   *
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
int i, j, k;
for(i = 1;i <= 4;i++)
{
for(j = 1;j < i;j++)
{
printf(" ");
}
for(k = 4;k >= i;k--)
{
printf("*");
}
printf("\n");
}
return 0;
}
Explanation: 1) The outer loop i runs from 1 to 4, one iteration per row. 2) The first inner loop prints (i-1) leading spaces, so row 1 has 0 spaces, row 2 has 1, and so on. 3) The second inner loop prints stars from k=4 down to k=i, giving 4,3,2,1 stars per row. 4) After each row a newline is printed, producing the right-aligned decreasing star pattern.
Q27.Easy
Write a C program to print a half diamond star pattern with 6 rows in the upper half and 5 rows in the lower half, like:
*
**
***
****
*****
******
*****
****
***
**
*
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int i, j;
    for (i = 1; i <= 6; i++) {
        for (j = 1; j <= i; j++) {
            printf("*");
        }
        printf("\n");
    }
    for (i = 1; i <= 5; i++) {
        for (j = i; j <= 5; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The outer loop for i from 1 to 6 prints the upper half: for each i, the inner loop prints i stars. 2. After the upper half, the outer loop for i from 1 to 5 prints the lower half: for each i, the inner loop runs from i to 5, printing (6-i) stars. 3. This produces 6 rows of increasing stars (1 to 6) followed by 5 rows of decreasing stars (5 to 1).
Q28.Easy
Write a C program that prints a right-angle triangle star pattern with 5 rows: row 1 has one '*', row 2 has two '*', row 3 has three '*', row 4 has four '*', and row 5 has five '*'. Each row must be printed on its own line.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int i, j;
    for(i = 1; i <= 5; i++)
    {
        for(j = 1; j <= i; j++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Outer loop i runs from 1 to 5, controlling the row number. 2) Inner loop j runs from 1 to i, so it prints exactly i stars in row i. 3) After the inner loop, printf("\n") ends the current row. 4) Row 1 prints 1 star, row 2 prints 2 stars, and so on up to row 5 with 5 stars. 5) Output: *, **, ***, ****, ***** each on a new line.
Q29.Easy
Write a C program that prints a mirrored right-angle triangle of 5 rows. In row 1 print four '0' characters followed by one '*'; in row 2 print three '0' characters followed by two '*'; and so on, until row 5 prints five '*' characters with no '0'. Each row ends with a newline.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int i, j, k;
    for(i = 1; i <= 5; i++)
    {
        for(j = 5; j > i; j--)
        {
            printf("0");
        }
        for(k = 1; k <= i; k++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Outer loop i runs from 1 to 5, one iteration per row. 2) Inner loop j starts at 5 and runs while j > i, printing (5 - i) zeros: row 1 gives 4 zeros, row 5 gives 0 zeros. 3) Second inner loop k runs from 1 to i, printing i stars: row 1 gives 1 star, row 5 gives 5 stars. 4) After both inner loops, printf("\n") moves to the next line. 5) Output: 0000*, 000**, 00***, 0****, *****.
Q30.Easy
Write a C program that prints the upper (top) half of a diamond star pattern using the digit 0 in place of spaces. For 5 rows, the output must be:
0000*
000***
00*****
0*******
*********
(Each row i from 1 to 5 has (5-i) zeros followed by (2*i-1) stars.)
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int i, j, k;
    for(i = 1; i <= 5; i++)
    {
        for(j = 5; j > i; j--)
        {
            printf("0");
        }
        for(k = 1; k <= (2*i - 1); k++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Outer loop i runs 1..5, one iteration per row. 2) Inner loop j prints (5-i) zeros to indent the row. 3) Second inner loop k prints (2*i-1) stars: row1=1, row2=3, ... row5=9. 4) After each row print a newline. 5) This produces the top half of the diamond with 0 as the space character.
Q31.Easy
Write a C program that prints the lower half of a diamond pattern with 4 rows using '0' for leading zeros and '*' for the rest. Row 1: 0 followed by 7 stars; Row 2: 00 followed by 5 stars; Row 3: 000 followed by 3 stars; Row 4: 0000 followed by 1 star. So the output is:
0*******
00*****
000***
0000*
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, j, k, m = 8;
    for (i = 1; i <= 4; i++)
    {
        for (j = 1; j <= i; j++)
        {
            printf("0");
        }
        for (k = i; k < m; k++)
        {
            printf("*");
        }
        m -= 1;
        printf("\n");
    }
    return 0;
}
Explanation: 1) Set m = 8, the number of characters (zeros + stars) in the first row. 2) Outer loop i goes 1 to 4, one row per iteration. 3) First inner loop prints i zeros (row 1 prints 1 zero, row 4 prints 4 zeros). 4) Second inner loop prints stars from k = i up to m-1, i.e. (m - i) stars: row 1 gives 7 stars, row 4 gives 1 star. 5) After each row, decrease m by 1 so the next row has 2 fewer stars, then print a newline.
Q32.Easy
Write a C program that reads an integer n from the user and prints a rhombus (parallelogram) star pattern of n rows, where each row has n stars and the rows are shifted right by one space each time (first row has n-1 leading spaces, last row has 0). For example, if the user enters 4, the output should be:
   ****
  ****
 ****
****
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, j, k, n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("\n");
    for (i = 0; i < n; i++)
    {
        for (k = 0; k < n - 1 - i; k++)
        {
            printf(" ");
        }
        for (j = 0; j < n; j++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n from the user. 2) Outer loop i runs from 0 to n-1, one iteration per row. 3) Inner loop k prints (n-1-i) spaces, so the first row is shifted most and the last row has no leading space. 4) Inner loop j prints exactly n stars. 5) Print a newline after each row, giving a slanted rhombus of stars.
Q33.Easy
Write a C program that prints an alphabet pyramid of 5 rows. Row i (1-based) has (5-i) leading spaces, then the letters A, B, C, ... in increasing order up to i letters, then the same letters in decreasing order back to A. For example, row 3 should be "  ABCBA" (two spaces then ABCBA).
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int i, j, k;
    char ch;
    for (i = 1; i <= 5; i++) {
        for (j = 5; j > i; j--)
            printf(" ");
        ch = 'A';
        for (k = 1; k <= i; k++)
            printf("%c", ch++);
        ch -= 2;
        for (k = 1; k < i; k++)
            printf("%c", ch--);
        printf("\n");
    }
    return 0;
}
Explanation: 1) Outer loop i runs from 1 to 5, one row per iteration. 2) First inner loop prints (5-i+1) spaces so the pyramid is centred. 3) Reset ch to 'A'; second inner loop prints i letters A,B,... increasing. 4) After that loop ch points one past the last printed letter, so subtract 2 to point at the letter just before the peak. 5) Third inner loop prints i-1 letters decreasing back to A. 6) Print a newline after each row.
Q34.Easy
Write a C program that reads an integer n from the user and prints a number pyramid of n rows. In row i (1-based), there are (n-i) leading spaces, then the numbers 1 to i in increasing order, then the numbers i-1 down to 1 in decreasing order. For example, if n = 4 the output should be:
   1
  121
 12321
1234321
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, j, k;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= n - i; j++)
            printf(" ");
        for (k = 1; k <= i; k++)
            printf("%d", k);
        for (k = i - 1; k >= 1; k--)
            printf("%d", k);
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n from the user. 2) Outer loop i runs from 1 to n, one row per iteration. 3) First inner loop prints (n-i) spaces to centre the row. 4) Second inner loop prints 1,2,...,i. 5) Third inner loop prints i-1,i-2,...,1 to complete the palindrome. 6) Print a newline after each row.
Q35.Easy
Write a C program that reads an integer n from the user and prints a solid square of '*' characters with n rows and n columns. For example, if n = 4 the output should be:

****
****
****
****
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the side length n. 2) The outer loop runs n times, once per row. 3) The inner loop runs n times per row and prints one '*' each time, so each row has n stars. 4) After finishing a row, print a newline to move to the next line. 5) The result is an n x n solid square of stars.
Q36.Easy
Write a C program to print a pyramid pattern of stars. The program should read the number of rows from the user and then print a pyramid where the first row has 1 star, the second row has 3 stars, and so on, with each row centered using spaces. For example, if the user enters 4, the output should be:
   *
  ***
 *****
*******
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int rows, spaces;
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    spaces = rows - 1;
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= spaces; j++) {
            printf(" ");
        }
        for (int k = 1; k <= 2 * i - 1; k++) {
            printf("*");
        }
        spaces--;
        printf("\n");
    }
    return 0;
}
Explanation: 1. Read the number of rows from the user. 2. Initialize spaces to rows - 1. 3. For each row i from 1 to rows: a. Print spaces number of spaces. b. Print (2*i - 1) stars. c. Decrease spaces by 1. d. Print a newline. 4. This creates a centered pyramid pattern.
Q37.Easy
Write a C program that prints an inverted pyramid star pattern. Read the number of rows n from the user. Row 1 has (2n-1) stars with no leading spaces; each next row has one more leading space and two fewer stars, so the last row has exactly 1 star centred under the first. For example, if n = 4 the output should be:
*******
 *****
  ***
   *
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int n;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    int spaces = 0;
    for (int i = n; i >= 1; i--)
    {
        for (int j = 1; j <= spaces; j++)
        {
            printf(" ");
        }
        for (int k = 1; k <= 2 * i - 1; k++)
        {
            printf("*");
        }
        spaces++;
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n. 2) Keep a counter spaces starting at 0. 3) Loop i from n down to 1: print 'spaces' leading spaces, then print (2*i - 1) stars, then a newline. 4) Increment spaces by 1 each row so the pyramid narrows and shifts right. 5) Row i = n gives 2n-1 stars with 0 spaces; row i = 1 gives 1 star with n-1 spaces — an inverted pyramid.
Q38.Easy
Write a C program that prints a half diamond star pattern. Read the number of rows n from the user, then print an increasing triangle of stars with rows of 1, 2, ..., n stars, followed by a decreasing triangle with rows of n-1, n-2, ..., 1 stars. For example, if n = 4 the output should be:
*
**
***
****
***
**
*
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int n;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            printf("*");
        }
        printf("\n");
    }
    for (int i = n - 1; i >= 1; i--)
    {
        for (int j = 1; j <= i; j++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n from the user. 2) First loop i from 1 to n: inner loop prints i stars, then a newline — this builds the growing half. 3) Second loop i from n-1 down to 1: inner loop prints i stars, then a newline — this builds the shrinking half. 4) Together they form a half diamond with 2n-1 rows.
Q39.Medium
Write a C program to print the following number pattern. Replace each 0 with a space. The pattern for 5 lines is:
    5
   45
  345
 2345
12345
(Note: The spaces before the numbers are shown as blanks; the numbers are printed without spaces between them.)
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int n = 5;
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++) {
            printf(" ");
        }
        for (int j = n - i + 1; j <= n; j++) {
            printf("%d", j);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The pattern has 5 lines. For line i (1 to 5), we print (5-i) spaces, then numbers from (5-i+1) to 5. 2. Use an outer loop for i from 1 to 5. 3. Inside, first inner loop prints spaces: runs from 1 to 5-i. 4. Second inner loop prints numbers: starts at 5-i+1 and goes up to 5. 5. After each line, print a newline. 6. This produces the required pattern.
Q40.Medium
Write a C program that prints a centred pyramid star pattern with 5 rows. Row 1 has 1 star, row 2 has 3 stars, row 3 has 5 stars, and so on (row i has 2i-1 stars), with leading spaces so the pyramid is centred. Use nested loops.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
int i, j, k;
for(i = 1;i <= 5;i++)
{
for(j = 5;j > i;j--)
{
printf(" ");
}
for(k = 1;k <= ((i*2)-1);k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Explanation: 1) Outer loop i runs 1 to 5 (one per row). 2) Inner loop j prints (5-i) leading spaces so the pyramid is centred. 3) Inner loop k prints (2i-1) stars for row i. 4) Print a newline after each row. 5) Output rows: 1, 3, 5, 7, 9 stars, each centred.
Q41.Medium
Write a C program that prints an inverted pyramid star pattern with 5 rows. The first row should have 9 stars, and each subsequent row should have 2 fewer stars, with the stars centred (leading spaces increase by 1 each row). Use nested loops.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
int i, j, k, m = 9;
for(i = 1;i <= 5;i++)
{
for(j = 1;j < i;j++)
{
printf(" ");
}
for(k = 1;k <= m;k++)
{
printf("*");
}
m = m - 2;
printf("\n");
}
return 0;
}
Explanation: 1) Set m = 9, the number of stars in the first row. 2) Outer loop i runs 1 to 5 (one per row). 3) Inner loop j prints (i-1) leading spaces so the pyramid is centred. 4) Inner loop k prints m stars. 5) After each row, reduce m by 2 so the next row has 2 fewer stars. 6) Print a newline after each row. Output rows: 9, 7, 5, 3, 1 stars.
Q42.Medium
Write a C program to print a mirror half diamond star pattern with 6 rows in the upper half and 5 rows in the lower half, where each row has leading spaces so that the stars are right-aligned, like:
     *
    **
   ***
  ****
 *****
******
 *****
  ****
   ***
    **
     *
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int i, j, k;
    for (i = 1; i <= 6; i++) {
        for (j = 6; j > i; j--) {
            printf(" ");
        }
        for (k = 1; k <= i; k++) {
            printf("*");
        }
        printf("\n");
    }
    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= i; j++) {
            printf(" ");
        }
        for (k = 5; k >= i; k--) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Upper half: for i from 1 to 6, first print (6-i) spaces using a loop j from 6 down to i+1, then print i stars. 2. Lower half: for i from 1 to 5, first print i spaces, then print (6-i) stars using a loop k from 5 down to i. 3. This creates a right-aligned diamond shape with 6 rows increasing and 5 rows decreasing.
Q43.Medium
Write a C program that prints a hollow diamond enclosed in a square of stars. For size 5 the output must be:
**********
****  ****
***    ***
**      **
*        *
**      **
***    ***
****  ****
**********
(The top half shrinks the inner gap as rows go down; the bottom half grows it back.)
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int i, j, k, m, a = 1, b = 0;
    for(i = 5; i > 0; i--)
    {
        for(j = i; j > 0; j--)
            printf("*");
        for(k = 1; k < a; k++)
            printf(" ");
        a = a + 2;
        for(m = i; m > 0; m--)
            printf("*");
        printf("\n");
    }
    for(i = 1; i <= 4; i++)
    {
        for(j = 0; j <= i; j++)
            printf("*");
        for(k = 6; k > b; k--)
            printf(" ");
        b = b + 2;
        for(m = 0; m <= i; m++)
            printf("*");
        printf("\n");
    }
    return 0;
}
Explanation: 1) First loop (i=5 down to 1) builds the top half: print i stars on the left, then (a-1) spaces starting with a=1 and increasing by 2 each row, then i stars on the right. 2) Row i=5 gives 5+0+5 stars = 10 stars (the full top edge); i=4 gives 4+2+4, and so on, forming the hollow V shape. 3) Second loop (i=1..4) builds the bottom half: print (i+1) stars, then (6-b) spaces with b starting 0 and increasing by 2, then (i+1) stars. 4) Together the two halves form the hollow diamond inside a star square.
Q44.Medium
Write a C program that prints a full diamond star pattern using '0' as the filler character for the left padding and '*' for the diamond. The top half has 5 rows: row i (1 to 5) prints (5-i) zeros, then (2*i-1) stars. The bottom half has 4 rows: row i (1 to 4) prints i zeros, then (9-2*i) stars. Each row ends with a newline.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int i, j, k;
    for(i = 1; i <= 5; i++)
    {
        for(j = 5; j > i; j--)
            printf("0");
        for(k = 1; k <= 2*i-1; k++)
            printf("*");
        printf("\n");
    }
    for(i = 1; i <= 4; i++)
    {
        for(j = 1; j <= i; j++)
            printf("0");
        for(k = 1; k <= 9-2*i; k++)
            printf("*");
        printf("\n");
    }
    return 0;
}
Explanation: 1) Top half: for i=1..5 print (5-i) zeros then (2*i-1) stars, giving widths 1,3,5,7,9. 2) Bottom half: for i=1..4 print i zeros then (9-2*i) stars, giving widths 7,5,3,1. 3) Newline after each row. Together the two halves form a symmetric diamond padded with zeros on the left.
Q45.Medium
Write a C program that prints the first part of a hollow diamond star pattern: a triangle of 5 rows where each row has leading spaces followed by two stars separated by increasing spaces (the top half of a hollow diamond). Specifically, for rows 1 to 5, print (5-row) spaces, then a star, then (2*row-3) spaces (none for row 1), then another star, then a newline. For row 1 print just a single star. Use a loop-based approach.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int row, s, gap;
    for(row = 1; row <= 5; row++)
    {
        for(s = row; s < 5; s++)
            printf(" ");
        printf("*");
        if(row > 1)
        {
            for(gap = 1; gap < 2*row-2; gap++)
                printf(" ");
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Loop row from 1 to 5. 2) Print (5-row) leading spaces so stars align into a triangle. 3) Print the first star. 4) For rows after the first, print (2*row-3) spaces then a second star, creating the hollow gap. 5) Newline after each row. This produces the top half of a hollow diamond.
Q46.Medium
Write a C program to print a hollow pyramid star pattern. The program should read an integer n (the number of rows) from the user and print a pyramid where the first row has one star, the last row is a solid line of stars, and the intermediate rows have stars at the edges with spaces inside. For example, if n = 5, the output should be:
    *
   * *
  *   *
 *     *
*********
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, j, k;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        // Print leading spaces
        for (k = 1; k <= n - i; k++)
            printf(" ");
        // Print stars and spaces for the pyramid
        for (j = 1; j <= 2 * i - 1; j++) {
            if (i == n || j == 1 || j == 2 * i - 1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Read the number of rows n from the user. 2. Loop i from 1 to n (each row). 3. For each row, print (n - i) leading spaces to center the pyramid. 4. Then print 2*i - 1 characters: a star if it's the first column (j==1), the last column (j==2*i-1), or the last row (i==n); otherwise a space. 5. After each row, print a newline. 6. This creates a hollow pyramid with a solid base.
Q47.Medium
Write a C program to print a hollow right-angled triangle star pattern. The program should read an integer n (the number of rows) from the user and print the pattern as described: the first row has one star, the last row has n stars, and for intermediate rows, there is a star at the beginning and at the end (with spaces in between). For example, if n = 5, the output should be:
*
**
* *
* *
*****
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, j;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= i; j++) {
            if (j == 1 || j == i || i == n)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Read the number of rows n from the user. 2. Loop i from 1 to n (each row). 3. For each row, loop j from 1 to i (columns up to current row). 4. Print a star if it's the first column (j==1), the last column (j==i), or the last row (i==n); otherwise print a space. 5. After each row, print a newline. 6. This creates a hollow right-angled triangle with the specified pattern.
Q48.Medium
Write a C program to print a mirrored hollow right angle triangle star pattern. The program should read an integer num from the user and print num lines. The pattern is right-aligned: each line starts with (num - i) spaces, followed by stars and spaces such that the first character after the spaces is a star, the last character is a star, and the interior is hollow except for the last line which is completely filled with stars. For example, if num = 5, the output should be:
    *
   **
  * *
 *  *
*****
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int i, j, k, num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("\n");
    for (i = 0; i < num; i++) {
        for (k = 0; k < num - i - 1; k++) {
            printf(" ");
        }
        for (j = 0; j <= i; j++) {
            if (j == 0 || j == i || i == num - 1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The program reads an integer num from the user. 2. The outer loop runs i from 0 to num-1, representing each row. 3. For each row, the first inner loop prints (num - i - 1) spaces to right-align the triangle. 4. The second inner loop runs j from 0 to i, printing a star if it is the first column (j==0), the last column (j==i), or the last row (i==num-1); otherwise, it prints a space. 5. After each row, a newline is printed. 6. This produces a mirrored hollow right angle triangle pattern.
Q49.Medium
Write a C program to print a pyramid pattern of stars with 5 rows, where each row i (1-indexed) has (2*i - 1) stars, and the stars are preceded by (5 - i) zeros. For example, the first row has 4 zeros followed by 1 star, the second row has 3 zeros followed by 3 stars, and so on.
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int i, j, k;
    for (i = 1; i <= 5; i++) {
        for (j = 5; j > i; j--) {
            printf("0");
        }
        for (k = 1; k <= (2 * i - 1); k++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The outer loop runs i from 1 to 5, representing each row. 2. For each row, the first inner loop prints (5 - i) zeros: for i=1, 4 zeros; i=2, 3 zeros; ... i=5, 0 zeros. 3. The second inner loop prints (2*i - 1) stars: for i=1, 1 star; i=2, 3 stars; ... i=5, 9 stars. 4. After printing zeros and stars, a newline is printed to move to the next row. 5. The program produces the desired pyramid pattern with leading zeros.
Q50.Medium
Write a C program that reads an integer n from the user and prints a hollow square of side n using '*' characters, with both diagonals also drawn with '*'. For example, if n = 5 the output should be:

*****
** **
* * *
** **
*****

(Every border cell, every main-diagonal cell and every anti-diagonal cell is a '*'; all other cells are spaces.)
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (i == 1 || i == n || j == 1 || j == n || i == j || j == n - i + 1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the side length n. 2) Use an outer loop i = 1..n for rows and an inner loop j = 1..n for columns. 3) Print '*' when the cell lies on the border (i==1, i==n, j==1, j==n), on the main diagonal (i==j) or on the anti-diagonal (j==n-i+1). 4) Otherwise print a space. 5) After each row print a newline. For n=5 this gives the hollow square with both diagonals shown.
Q51.Medium
Write a C program to print a right arrow star pattern. Read the number of columns n from the user. For n = 5 the output should be:
*****
 ****
  ***
   **
    *
   **
  ***
 ****
*****
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter the number of columns");
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < i; j++)
            printf(" ");
        for (int k = 1; k <= n - i; k++)
            printf("*");
        printf("\n");
    }
    for (int i = 1; i < n; i++)
    {
        for (int j = 1; j < n - i; j++)
            printf(" ");
        for (int k = 1; k <= i + 1; k++)
            printf("*");
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n (number of columns). 2) Upper part: for each row i from 0 to n-1, print i leading spaces, then (n-i) stars, then a newline. Row 0 gives n stars, row n-1 gives 1 star. 3) Lower part: for each row i from 1 to n-1, print (n-i-1) leading spaces, then (i+1) stars, then a newline. This grows the star count back to n. 4) Together the rows form a right-pointing arrow shape. 5) For n = 5 the rows are: 5 stars, 4 stars, 3 stars, 2 stars, 1 star, then 2, 3, 4, 5 stars with increasing leading spaces.
Q52.Medium
Write a C program that prints a left-pointing arrow made of '*' characters. Read an integer n (number of columns) from the user. The upper part has n rows: row i (1 to n) prints (n-i) spaces followed by (n-i+1) stars. The lower part has n-1 rows: row i (1 to n-1) prints i spaces followed by (i+1) stars. For example, if n = 4 the output should be:

   ****
  ***
 **
*
 **
  ***
   ****
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter the number of columns: ");
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            printf(" ");
        }
        for (int k = 0; k <= n - i; k++) {
            printf("*");
        }
        printf("\n");
    }
    for (int i = 1; i < n; i++) {
        for (int j = 1; j <= i; j++) {
            printf(" ");
        }
        for (int k = 1; k <= i + 1; k++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Read integer n. 2. Upper part: for i = 1 to n, print (n-i) spaces then (n-i+1) stars, then newline. This shrinks the star block each row, forming the top half of the arrow. 3. Lower part: for i = 1 to n-1, print i spaces then (i+1) stars, then newline. This grows the star block again, forming the bottom half. 4. Together the two halves form a left-pointing arrow.
Q53.Medium
Write a C program that prints a plus (+) pattern using the character '+'. The program should read an odd number n (the size of the pattern) from the user and print an n×n grid where the middle row is completely filled with '+' and every other row has a single '+' in the middle column. For example, if n = 5 the output should be:

  +
  +
+++++
  +
  +
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter an odd number: ");
    scanf("%d", &n);
    int mid = n / 2 + 1;
    for (int i = 1; i <= n; i++) {
        if (i == mid) {
            for (int j = 1; j <= n; j++) {
                printf("+");
            }
        } else {
            for (int j = 1; j <= n / 2; j++) {
                printf(" ");
            }
            printf("+");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. Read an odd integer n from the user. 2. Compute the middle row index mid = n/2 + 1. 3. Loop i from 1 to n (each row). 4. If i equals mid, print n '+' characters to form the horizontal bar. 5. Otherwise print n/2 spaces followed by a single '+' so the vertical bar lines up in the middle column. 6. Print a newline after each row.

Other questions

Q54.Easy
Write a C program that reads the order of two matrices (up to 10 x 10), reads the elements of matrix A and matrix B, and prints their sum matrix (element-wise addition).
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 the matrices (rows cols): \n");
    scanf("%d %d", &rows, &cols);
    printf("Enter the elements of matrix A:\n");
    for(i = 0; i < rows; i++)
        for(j = 0; j < cols; j++)
            scanf("%d", &a[i][j]);
    printf("Enter the elements of matrix B:\n");
    for(i = 0; i < rows; i++)
        for(j = 0; j < cols; j++)
            scanf("%d", &b[i][j]);
    printf("Matrix 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 10x10 integer arrays a and b and read the number of rows and columns. 2) Use nested loops to read all elements of matrix A, then all elements of matrix B. 3) For addition the matrices must have the same order, so reuse the same rows and cols. 4) Use nested loops again to print a[i][j] + b[i][j] for every position, giving the sum matrix. 5) Print a newline after each row so the output appears as a proper matrix.
Q55.Easy
Write a C program that reads an integer from the user and prints its multiplication table from 1 to 10, in the format shown. For example, if the user enters 7, the output should be:
1 * 7 = 7
2 * 7 = 14
3 * 7 = 21
4 * 7 = 28
5 * 7 = 35
6 * 7 = 42
7 * 7 = 49
8 * 7 = 56
9 * 7 = 63
10 * 7 = 70
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n, i;
    printf("Enter a number : ");
    scanf("%d", &n);
    for(i = 1; i <= 10; i++)
    {
        printf("\n%d * %d = %d", i, n, i * n);
    }
    return 0;
}
Explanation: 1. Declare two integers: n (the table number) and i (the multiplier). 2. Read the number n from the user using scanf. 3. Start a for loop with i = 1 and run it while i <= 10, incrementing i each time. 4. Inside the loop print i, n and their product i*n in the format 'i * n = product'. 5. The loop prints 10 lines, giving the full multiplication table of n.
Q56.Easy
Write a C program that acts as a simple arithmetic calculator. Read two integers from the user, then display a menu: 1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division, and any other key to exit. Read the user's choice and use a switch statement to perform the selected operation, printing the result in the form 'a op b = result'. For example, if the user enters 15 and 4 and then chooses 1, the program should print '15 + 4 = 19'.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int num1, num2, choice, answer;
    printf("Enter any two integers : ");
    scanf("%d %d", &num1, &num2);
    printf("\nPress 1 for Addition");
    printf("\nPress 2 for Subtraction");
    printf("\nPress 3 for Multiplication");
    printf("\nPress 4 for Division");
    printf("\nPress other key to exit");
    printf("\n\nEnter your choice : ");
    scanf("%d", &choice);
    switch (choice)
    {
        case 1:
            answer = num1 + num2;
            printf("\n%d + %d = %d", num1, num2, answer);
            break;
        case 2:
            answer = num1 - num2;
            printf("\n%d - %d = %d", num1, num2, answer);
            break;
        case 3:
            answer = num1 * num2;
            printf("\n%d * %d = %d", num1, num2, answer);
            break;
        case 4:
            answer = num1 / num2;
            printf("\n%d / %d = %d", num1, num2, answer);
            break;
        default:
            printf("\nInvalid Choice");
    }
    return 0;
}
Explanation: 1) Read two integers num1 and num2 with scanf. 2) Print the menu options for addition, subtraction, multiplication, division and exit. 3) Read the user's choice. 4) Use switch(choice): case 1 adds, case 2 subtracts, case 3 multiplies, case 4 divides, and default prints 'Invalid Choice'. 5) Each case computes the answer and prints it in the form 'num1 op num2 = answer', then breaks. Example: inputs 15 and 4 with choice 1 gives '15 + 4 = 19'.
Q57.Easy
Write a C program that asks the user for a limit n, then reads n integers in a loop, and prints the biggest of them. Use two temporary variables: store the first number in temp1, and for each subsequent number stored in temp2, update temp1 if temp2 is greater.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int num, limit, i, temp1 = 0, temp2 = 0;
    printf("\nEnter the limit : ");
    scanf("%d", &limit);
    for(i = 0; i < limit; i++)
    {
        printf("\nEnter number %d : ", i + 1);
        scanf("%d", &num);
        if(i == 0)
            temp1 = num;
        else
        {
            temp2 = num;
            if(temp2 > temp1)
                temp1 = temp2;
        }
    }
    printf("The biggest number is %d", temp1);
    return 0;
}
Explanation: 1. Read the limit n. 2. In the loop, read each number into 'num'. 3. For the first number (i==0), store it in temp1 as the current maximum. 4. For every later number, store it in temp2 and if temp2 > temp1, set temp1 = temp2. 5. After the loop, temp1 holds the biggest number, which is printed.
Q58.Easy
Write a C program to find the largest among n numbers entered by the user. First, read the count n, then read n numbers one by one, and finally display the largest number. Use a temporary variable to keep track of the maximum.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, num, max = 0;

    printf("Enter how many numbers: ");
    scanf("%d", &n);

    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &num);
        if (i == 0 || num > max) {
            max = num;
        }
    }

    printf("The largest number is %d\n", max);
    return 0;
}
Explanation: 1. Declare variables: n for count, num for each input, and max initialized to 0 to store the largest. 2. Read the value of n from the user. 3. Use a loop that runs n times: in each iteration, read a number into num. 4. Compare num with max; if num is greater, update max = num. 5. After the loop, print the value of max as the largest number.
Q59.Easy
Write a C program to subtract two matrices of the same order. The program should first read the number of rows and columns (up to 10 each), then read the elements of the first matrix, then the elements of the second matrix, and finally print the resulting matrix after subtraction.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int rows, cols;
    int A[10][10], B[10][10], C[10][10];
    int i, j;

    printf("Enter the number of rows and columns (max 10): ");
    scanf("%d %d", &rows, &cols);

    printf("Enter elements of matrix A:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    printf("Enter elements of matrix B:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            C[i][j] = A[i][j] - B[i][j];
        }
    }

    printf("Result of matrix subtraction:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("%4d", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Explanation: 1. Declare two 2D arrays A and B of size 10x10 to store the input matrices, and another array C for the result. 2. Read the number of rows and columns from the user. 3. Use nested loops to read the elements of matrix A. 4. Similarly, read the elements of matrix B. 5. Subtract corresponding elements: C[i][j] = A[i][j] - B[i][j] for each i and j. 6. Print the resulting matrix C row by row, formatting each number with width 4 for alignment.
Q60.Easy
Write a C program that prints the message "Welcome to C programming!" to the screen.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    printf("Welcome to C programming!\n");
    return 0;
}
Explanation: 1. Include the standard I/O header <stdio.h> to use printf. 2. Define the main function as int main(). 3. Use printf to display the required message. 4. Return 0 to indicate successful execution.
Q61.Easy
Write a C program that declares an int variable named TOTAL (all uppercase letters) and initializes it to 7, then prints its value in the format: The value of TOTAL = 7
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int TOTAL = 7;
    printf("The value of TOTAL = %d\n", TOTAL);
    return 0;
}
Explanation: 1. Include <stdio.h> so printf is available. 2. In main, declare an int named TOTAL and set it to 7. Uppercase letters are allowed in identifiers (though using them for ordinary variables is considered poor style), so this compiles fine. 3. printf prints the text 'The value of TOTAL = ' followed by %d, which is replaced by the value of TOTAL (7). 4. return 0 ends the program successfully.
Q62.Easy
Write a C program that declares a constant integer named LIMIT with value 50 using the const keyword, prints its value, and includes a commented-out line showing that modifying it would cause a compile error.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    const int LIMIT = 50;
    printf("The value of LIMIT = %d\n", LIMIT);
    /* LIMIT = LIMIT + 1;  // ERROR: assignment to read-only variable */
    return 0;
}
Explanation: 1. const int LIMIT = 50; declares LIMIT as a read-only variable initialised to 50. 2. printf prints the value 50. 3. Any attempt such as LIMIT = LIMIT + 1 would be rejected by the compiler because LIMIT is read-only, so that line is kept only as a comment. 4. The program ends with return 0.
Q63.Easy
Write a C program that demonstrates a constant value defined WITHOUT using the const keyword. Define a constant named MAX_MARKS with value 75 using a preprocessor directive, print its value, and then show (in a comment) that trying to change it would cause a compile error.
Show answer & explanation
Answer:
#include <stdio.h>
#define MAX_MARKS 75
int main()
{
    printf("The value of MAX_MARKS = %d\n", MAX_MARKS);
    /* MAX_MARKS = MAX_MARKS + 1;  // ERROR: cannot assign to a macro constant */
    return 0;
}
Explanation: 1. #define MAX_MARKS 75 creates a macro constant; the preprocessor replaces every MAX_MARKS with 75 before compilation. 2. Because it is a macro, there is no variable to assign to, so a statement like MAX_MARKS = MAX_MARKS + 1 would be expanded to 75 = 75 + 1, which is invalid and causes a compile error. 3. The program simply prints the constant value 75 and exits with return 0.
Q64.Easy
Write a C program to demonstrate the purpose of a volatile variable. Declare a volatile integer variable named 'total' and initialize it to 10. Then increment its value by 5 and print the result.
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    volatile int total = 10;
    total = total + 5;
    printf("The value of total = %d\n", total);
    return 0;
}
Explanation: 1. Include stdio.h for printf. 2. In main, declare volatile int total = 10. 3. Increment total by 5: total = total + 5, so total becomes 15. 4. Print the value using printf. 5. Return 0 to end the program.
Q65.Easy
Write a C program to demonstrate the purpose of a volatile variable. Declare an integer variable named 'count' and initialize it to 5. Then increment its value by 3 and print the result. Do not use the volatile keyword.
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int count = 5;
    count = count + 3;
    printf("The value of count = %d\n", count);
    return 0;
}
Explanation: 1. Include stdio.h for printf. 2. In main, declare int count = 5. 3. Increment count by 3: count = count + 3, so count becomes 8. 4. Print the value using printf. 5. Return 0 to end the program.
Q66.Easy
Write a C program that declares a char variable named 'grade' and assigns it the character 'A'. Then print the character using printf in the format: "The character of grade = A" (without quotes).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    char grade = 'A';
    printf("The character of grade = %c", grade);
    return 0;
}
Explanation: 1. Include <stdio.h> for printf. 2. Define main() with int return type. 3. Declare a char variable 'grade' and initialize it to 'A'. 4. Use printf with %c to print the character. 5. Return 0.
Q67.Easy
Write a C program that declares an integer variable named 'marks' and assigns it the value 75. Then print the value using printf in the format: "The value of marks = 75" (without quotes).
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int marks = 75;
    printf("The value of marks = %d", marks);
    return 0;
}
Explanation: 1. Include the standard input-output header <stdio.h> for printf. 2. Define main() with return type int. 3. Declare an integer variable 'marks' and initialize it to 75. 4. Use printf with format specifier %d to print the integer value. 5. Return 0 to indicate successful execution.
Q68.Easy
Write a C program that stores the decimal value 5.123456789 in a float variable and prints it with 9 digits after the decimal point using the %0.9f format specifier.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    float rate = 5.123456789;
    printf("The value of rate = %0.9f", rate);
    return 0;
}
Explanation: 1. Include <stdio.h> for printf. 2. Declare a float variable 'rate' and assign 5.123456789 (float stores decimals, typically 4 bytes, so precision is limited). 3. Use printf with %0.9f to print 9 digits after the decimal point. 4. Return 0 to end main.
Q69.Easy
Write a C program that stores the decimal value 12.345678901 in a double variable and prints it using the %lf format specifier.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    double price = 12.345678901;
    printf("The value of price = %lf", price);
    return 0;
}
Explanation: 1. Include <stdio.h> for printf. 2. Declare a double variable 'price' and assign 12.345678901 (double holds high-precision decimals, typically 8 bytes). 3. Use printf with %lf to print the double value. 4. Return 0 to end main.
Q70.Easy
Write a C program that declares two int variables, one named total with value 150 and another named Total with value 275, and prints both values using %d to show that C identifiers are case-sensitive.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int total = 150;
    int Total = 275;
    printf("The total is %d ", total);
    printf("\nThe Total is %d ", Total);
    return 0;
}
Explanation: Step 1: Include <stdio.h> for printf. Step 2: Declare int total = 150. Step 3: Declare int Total = 275 — different identifier because C is case-sensitive. Step 4: Print total with %d, then print Total with %d on a new line. Step 5: Output shows 150 and 275, proving total and Total are treated as separate variables.
Q71.Easy
Write a C program that declares two integer variables: one named 'marks' with value 85 and another named 'Marks' with value 92. Print both values with appropriate labels to demonstrate that C is case-sensitive and that variable names can differ only by case.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int marks = 85;
    int Marks = 92;
    printf("The marks is %d\n", marks);
    printf("The Marks is %d\n", Marks);
    return 0;
}
Explanation: 1. Include the standard input-output library. 2. In main, declare an integer variable 'marks' and initialize it to 85. 3. Declare another integer variable 'Marks' (capital M) and initialize it to 92. C is case-sensitive, so these are two distinct variables. 4. Print the value of 'marks' with a label. 5. Print the value of 'Marks' with a label. 6. Return 0 to indicate successful execution.
Q72.Easy
Write a C program that reads an array of integers from the user, calculates the sum of all elements, and then checks whether the sum is divisible by the number of elements. If it is divisible, print "<sum> is divisible by <count>"; otherwise print "<sum> is not divisible by <count>". Assume the array size is at most 20.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, sum = 0;
    int arr[20];
    printf("Enter array size : ");
    scanf("%d", &n);
    printf("Enter elements : ");
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    for (i = 0; i < n; i++) {
        sum += arr[i];
    }
    if (sum % n == 0)
        printf("%d is divisible by %d\n", sum, n);
    else
        printf("%d is not divisible by %d\n", sum, n);
    return 0;
}
Explanation: 1. Declare variables: n for size, sum initialized to 0, and an array arr of size 20. 2. Prompt the user to enter the array size and read it into n. 3. Prompt the user to enter the elements and read them into arr using a loop. 4. Use another loop to add each element to sum. 5. Check if sum is divisible by n using the modulo operator (sum % n == 0). 6. Print the appropriate message based on the divisibility check.
Q73.Easy
Write a C program that takes the name and monthly salary of two employees as input from the user and writes them to a text file named "staff.txt" in the following format:
    name1, 4500
    name2, 8200
(Each line should contain the name, a comma, a space, and the salary.)
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    char name1[50], name2[50];
    int salary1, salary2;
    FILE *fp;

    printf("Enter name and salary of employee 1: ");
    scanf("%49s %d", name1, &salary1);
    printf("Enter name and salary of employee 2: ");
    scanf("%49s %d", name2, &salary2);

    fp = fopen("staff.txt", "w");
    if (fp == NULL) {
        printf("Could not open file.\n");
        return 1;
    }

    fprintf(fp, "%s, %d\n", name1, salary1);
    fprintf(fp, "%s, %d\n", name2, salary2);

    fclose(fp);
    printf("Data written to staff.txt\n");
    return 0;
}
Explanation: 1. Declare two character arrays for names and two int variables for salaries. 2. Use scanf to read each employee's name and salary from the user. 3. Open "staff.txt" in write mode ("w") using fopen; check for NULL. 4. Use fprintf with format "%s, %d\n" to write each employee on its own line in the required format. 5. Close the file with fclose so the data is saved.
Q74.Easy
Write a C statement that opens a file named "marks.dat" located in the current directory for reading in binary mode. Store the file pointer in a variable named fp.
Show answer & explanation
Answer:
fp = fopen("marks.dat", "rb");
Explanation: 1. Use fopen() to open a file in C. 2. First argument is the file name as a string: "marks.dat". 3. Second argument is the mode string. For reading in binary mode use "rb" (r = read, b = binary). 4. Assign the returned FILE pointer to fp: fp = fopen("marks.dat", "rb"); 5. (Good practice: check if fp == NULL before using it.)
Q75.Easy
In C, what happens when a file that already exists with some content is opened using fopen with mode "w"? Write a small C program that opens an existing file "notes.txt" in "w" mode and then writes the text "Hello" into it, and state clearly what happens to the old content.
Show answer & explanation
Answer:
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("notes.txt", "w");
    if (fp == NULL) {
        printf("File could not be opened\n");
        return 1;
    }
    fprintf(fp, "Hello");
    fclose(fp);
    printf("Done\n");
    return 0;
}
Explanation: 1. Opening an existing file with mode "w" truncates it to zero length, i.e. all previous content is erased. 2. If the file does not exist, "w" creates a new empty file. 3. The program opens notes.txt in "w" mode, so any old data in it is lost immediately on opening. 4. It then writes "Hello" using fprintf and closes the file with fclose, leaving notes.txt containing only "Hello".
Q76.Easy
Write a C program that prints the natural numbers from 10 to 20 (both inclusive), each on a new line, using a for loop whose counter variable i is initialized to 0.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int i;
    for (i = 0; i <= 20; i++) {
        if (i >= 10) {
            printf("%d\n", i);
        }
    }
    return 0;
}
Explanation: 1) The counter i must start at 0 as required. 2) Loop while i <= 20. 3) Only print when i >= 10, so numbers below 10 are skipped. 4) This prints 10,11,...,20 each on a new line.
Q77.Easy
Write a C program that reads an integer n from the user and prints the first n natural numbers (1 to n), each on a new line, using a for loop.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i;
    printf("Enter n: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        printf("%d\n", i);
    }
    return 0;
}
Explanation: 1) Declare n and loop counter i. 2) Read n with scanf. 3) The for loop starts i at 1 and runs while i <= n, incrementing i each time. 4) Inside the loop, print i followed by a newline. 5) So the output is 1,2,...,n each on its own line.
Q78.Easy
Write a C program that reads a number n and prints the first n natural numbers in reverse order (from n down to 1). For example, if n = 6, the output should be: 6 5 4 3 2 1.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n, i;
    printf("Enter n : ");
    scanf("%d", &n);
    for(i = n; i >= 1; i--)
        printf("%d ", i);
    return 0;
}
Explanation: 1) Read the value of n from the user. 2) Start a loop with i = n. 3) On each pass print i, then decrease i by 1. 4) Continue while i >= 1, so the numbers print from n down to 1. 5) The loop stops after printing 1.
Q79.Easy
Write a C program that reads n integers from the user and prints them in descending order (largest first). For example, if the user enters 5 numbers: 41 38 45 36 40, the program should print: 45 41 40 38 36.
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("----Descending Order----\n");
    for(i = 0; i < n; i++)
        printf("%d ", a[i]);
    return 0;
}
Explanation: 1) Read n, the count of numbers. 2) Read the n integers into array a. 3) Use a nested loop: for each position i, compare a[i] with every later element a[j]. 4) If a[i] < a[j], swap them so the larger value moves to position i. 5) After the loops the array is sorted largest to smallest. 6) Print the array in order.
Q80.Easy
Write a C program that reads an integer from the user and prints whether it is Even or Odd. For example, if the user enters 7, the program should print Odd.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int num;
    printf("Enter the number : ");
    scanf("%d", &num);
    if (num % 2 == 0)
        printf("Even\n");
    else
        printf("Odd\n");
    return 0;
}
Explanation: 1) Declare an integer num and read it with scanf. 2) Compute num % 2, the remainder when divided by 2. 3) If the remainder is 0 the number is divisible by 2, so print Even; otherwise print Odd. 4) For num = 7, 7 % 2 = 1 (not 0), so the program prints Odd.
Q81.Easy
Write a C program that reads an integer from the user and prints its factorial. For example, if the user enters 6, the program should print the factorial of 6.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int n, i;
    long long fact = 1;
    printf("Enter a number: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
    {
        fact *= i;
    }
    printf("Factorial of %d is %lld\n", n, fact);
    return 0;
}
Explanation: 1) Declare n for the input and fact = 1 to hold the running product. 2) Read the number n with scanf. 3) Loop i from 1 to n, multiplying fact by i each time (fact = 1*2*3*...*n). 4) After the loop, print the value of fact. 5) For n = 6 the loop gives 1*2*3*4*5*6 = 720, so it prints 'Factorial of 6 is 720'.
Q82.Easy
Write a C program that reads an integer from the user and prints its factorial. For example, if the user enters 6, the program should print 720.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int i, fact = 1, num;
    printf("Enter a number: ");
    scanf("%d", &num);
    for (i = 1; i <= num; i++) {
        fact = fact * i;
    }
    printf("Factorial of %d is: %d", num, fact);
    return 0;
}
Explanation: 1) Declare fact = 1, which is the multiplicative identity. 2) Read the number num from the user with scanf. 3) Run a for loop from i = 1 to i = num. 4) In each iteration multiply fact by i, so fact becomes 1*2*3*...*num. 5) After the loop print fact, e.g. for num = 6 the loop gives 720.
Q83.Easy
Write a C program that reads an integer n from the user and prints the first n Fibonacci numbers, where the series starts with 0 and 1. For example, if the user enters 6, the output should be: 0 1 1 2 3 5
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int a = 0, b = 1, c, i, n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n < 1)
    {
        printf("Invalid input\n");
    }
    else if (n == 1)
    {
        printf("%d\n", a);
    }
    else
    {
        printf("%d %d", a, b);
        for (i = 3; i <= n; i++)
        {
            c = a + b;
            a = b;
            b = c;
            printf(" %d", c);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read n from the user. 2) If n < 1, print an invalid-input message. 3) If n == 1, print only the first term 0. 4) Otherwise print the first two terms 0 and 1, then loop from i = 3 to n. 5) In each iteration compute c = a + b, shift a = b and b = c, and print c. 6) For n = 6 the printed terms are 0 1 1 2 3 5.
Q84.Easy
Write a C program that reads two non-negative integers from the user and prints their GCD (greatest common divisor) using a recursive function. For example, if the user enters 0 and 8, the output should be: G.C.D of 0 and 8 = 8
Show answer & explanation
Answer:
#include <stdio.h>
int gcd(int a, int b);
int main()
{
    int a, b;
    printf("Enter two non-negative integers: ");
    scanf("%d %d", &a, &b);
    printf("G.C.D of %d and %d = %d\n", a, b, gcd(a, b));
    return 0;
}
int gcd(int a, int b)
{
    if (b != 0)
        return gcd(b, a % b);
    else
        return a;
}
Explanation: 1) Read two integers a and b from the user. 2) Define a recursive function gcd(a, b): if b is not 0, call gcd(b, a % b); otherwise return a. 3) This is the Euclidean algorithm: the GCD of a and b equals the GCD of b and a mod b. 4) When b becomes 0, the remaining value a is the GCD. 5) Print the result in the format 'G.C.D of a and b = result'. For input 0 and 8: gcd(0,8)->gcd(8,0)->returns 8.
Q85.Easy
Write a C program to find the LCM (Least Common Multiple) of two positive integers entered by the user. For example, if the user enters 15 and 20, the program should print 'LCM of 15 and 20 is 60'.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int a, b, max;
    printf("Enter two positive integers: ");
    scanf("%d %d", &a, &b);
    max = (a > b) ? a : b;
    while (1) {
        if (max % a == 0 && max % b == 0) {
            printf("LCM of %d and %d is %d\n", a, b, max);
            break;
        }
        max++;
    }
    return 0;
}
Explanation: 1) Read the two integers a and b. 2) Start checking from the larger of the two, since the LCM cannot be smaller than the larger number. 3) In an infinite loop, test whether the current value is divisible by both a and b. 4) The first such value is the LCM; print it and break out of the loop. 5) Example: for 15 and 20, checking 20,21,... reaches 60, which is divisible by both, so LCM = 60.
Q86.Easy
Write a C program that performs a linear search on an array of integers. The program should read the number of elements, then the elements themselves, then a value to search for. It should print the 1-based position of the FIRST occurrence of the value if found, otherwise print that the value is not present. Use a separate function that returns the index (or -1 if not found).
Show answer & explanation
Answer:
#include <stdio.h>

int linearSearch(int arr[], int n, int key) {
    int i;
    for (i = 0; i < n; i++) {
        if (arr[i] == key)
            return i;
    }
    return -1;
}

int main() {
    int arr[100], n, key, i, pos;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d integers: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    printf("Enter value to search: ");
    scanf("%d", &key);
    pos = linearSearch(arr, n, key);
    if (pos != -1)
        printf("%d found at position %d\n", key, pos + 1);
    else
        printf("%d not found in the array\n", key);
    return 0;
}
Explanation: 1) The function linearSearch loops from index 0 to n-1 comparing each element with the key. 2) On the first match it returns that index, so the first occurrence is reported. 3) If the loop finishes without a match it returns -1. 4) main reads n, the array elements and the key, calls the function, and prints position (index+1) if found, else a 'not found' message.
Q87.Easy
Write a C program that searches an array for a given value and prints every position (1-based) where the value occurs, along with the total number of occurrences. If the value is absent, print a not-found message.
Show answer & explanation
Answer:
#include <stdio.h>
int main()
{
    int arr[100], n, i, key, count = 0;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    printf("Enter value to search: ");
    scanf("%d", &key);
    for (i = 0; i < n; i++)
    {
        if (arr[i] == key)
        {
            printf("%d is present at position %d.\n", key, i + 1);
            count++;
        }
    }
    if (count == 0)
        printf("%d is not present in the array.\n", key);
    else
        printf("%d occurs %d time(s) in the array.\n", key, count);
    return 0;
}
Explanation: 1. main reads n and then n array elements, followed by the search key. 2. A counter count is initialised to 0. 3. The loop scans all indices; whenever arr[i]==key it prints the 1-based position i+1 and increments count. 4. After the loop, if count is 0 it prints a not-found message; otherwise it prints how many times the key occurred.
Q88.Easy
Write a C program that performs a linear search using a separate function. The program should read the number of elements, read the elements into an array, read the value to search for, call a function to find its position, and print the position (1-based) or a not-found message.
Show answer & explanation
Answer:
#include <stdio.h>
int linear_search(int arr[], int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
    {
        if (arr[i] == key)
            return i;
    }
    return -1;
}

int main()
{
    int arr[100], n, i, key, pos;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);
    printf("Enter value to search: ");
    scanf("%d", &key);
    pos = linear_search(arr, n, key);
    if (pos == -1)
        printf("%d is not present in the array.\n", key);
    else
        printf("%d is present at position %d.\n", key, pos + 1);
    return 0;
}
Explanation: 1. The function linear_search takes the array, its size and the key, loops from index 0 to n-1 and returns the first index where arr[i]==key, or -1 if not found. 2. main reads n, then n elements into arr, then the key. 3. It calls linear_search and stores the returned index in pos. 4. If pos is -1 it prints a not-found message; otherwise it prints pos+1 to show a 1-based position.
Q89.Easy
Write a C program to print the following number pattern using nested loops. The pattern has 5 lines. On the first line, print the digit 1 once. On the second line, print the digit 2 twice. On the third line, print the digit 3 three times, and so on, until the fifth line prints the digit 5 five times. Use three for loops: the outer loop controls the line number (1 to 5), the second loop prints the current line number repeatedly, and the third loop is not needed; actually, only two loops are required. However, the problem statement mentions three for loops; you may use two loops to achieve the pattern.
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int i, j;
    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= i; j++) {
            printf("%d", i);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The outer loop runs for i = 1 to 5, representing each line. 2. For each line, the inner loop runs j = 1 to i, printing the value of i each time. 3. After the inner loop, a newline is printed to move to the next line. 4. So, line 1 prints '1' once, line 2 prints '2' twice, ..., line 5 prints '5' five times.
Q90.Easy
Write a C program to print the following number pattern using nested loops. The pattern has 5 lines. On the first line, print numbers from 1 to 5 consecutively (i.e., 12345). On the second line, print numbers from 2 to 5 (i.e., 2345), and so on, until the fifth line prints only 5. Use two for loops: the outer loop controls the line number and the starting value, and the inner loop prints the numbers from the current starting value up to 5.
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int line, num;
    for (line = 1; line <= 5; line++) {
        for (num = line; num <= 5; num++) {
            printf("%d", num);
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1. The outer loop runs for line = 1 to 5, representing each line of the pattern. 2. For each line, the inner loop starts at num = line and goes up to 5, printing the numbers consecutively. 3. After the inner loop finishes, a newline is printed to move to the next line. 4. Thus, the first line prints 1 to 5, the second line prints 2 to 5, and so on, until the fifth line prints only 5.
Q91.Easy
Write a C program that prints a mirrored right-angled triangle of stars with 5 rows. Row 1 has 4 spaces followed by 1 star, row 2 has 3 spaces followed by 2 stars, and so on, so that row 5 has 0 spaces followed by 5 stars. Use nested for loops (one loop for the leading spaces, one for the stars).
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
int i, j, k;
for(i = 1; i <= 5; i++)
{
for(j = 5; j > i; j--)
{
printf(" ");
}
for(k = 1; k <= i; k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Explanation: Step 1: The outer loop runs i from 1 to 5, once per row. Step 2: The first inner loop runs j from 5 down to i+1, printing (5 - i) spaces: row 1 gets 4 spaces, row 5 gets 0. Step 3: The second inner loop runs k from 1 to i, printing i stars: row 1 gets 1 star, row 5 gets 5. Step 4: printf("\n") ends each row, giving a right-aligned (mirrored) triangle.
Q92.Easy
Write a C program that prints an inverted right-angled triangle of stars with 5 rows: the first row has 5 stars, the second row has 4 stars, and so on down to the last row with 1 star. Use nested for loops (an outer loop for each row and an inner loop for the stars in that row).
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = i; j <= 5; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Explanation: Step 1: The outer loop runs i from 1 to 5, once for each row. Step 2: For row i, the inner loop runs j from i to 5, so it prints (6 - i) stars: row 1 prints 5 stars, row 2 prints 4, ... row 5 prints 1. Step 3: After the inner loop finishes, printf("\n") moves to the next line. Step 4: The result is an inverted triangle: 5 stars, then 4, 3, 2, 1.
Q93.Easy
Write a C program to check whether a given number is prime or not. The program should read an integer from the user and print whether it is prime or not. For example, if the input is 111, the output should be "111 is not a prime number".
Show answer & explanation
Answer:
#include <stdio.h>
int main() {
    int num, i, isPrime = 1;
    printf("Enter a number to check if it is prime: ");
    scanf("%d", &num);
    if (num <= 1) {
        isPrime = 0;
    } else {
        for (i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }
    if (isPrime)
        printf("%d is a prime number", num);
    else
        printf("%d is not a prime number", num);
    return 0;
}
Explanation: 1. We declare variables: num to store the input, i for loop counter, and isPrime flag initialized to 1 (true). 2. Read an integer from the user using scanf. 3. If num is less than or equal to 1, it is not prime, so set isPrime = 0. 4. Otherwise, loop i from 2 to num/2. For each i, check if num is divisible by i (num % i == 0). If yes, set isPrime = 0 and break out of the loop. 5. After the loop, if isPrime is still 1, print that num is prime; else print that it is not prime. 6. For input 111, the loop checks divisors up to 55. It finds that 111 % 3 == 0, so isPrime becomes 0, and it prints "111 is not a prime number".
Q94.Easy
Write a C program to check whether a given number is prime or not. The program should read an integer from the user and print "prime" if it is a prime number, otherwise print "not prime". For example, if the input is 44, output should be "not prime"; if input is 7, output should be "prime".
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int n, i, flag = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n <= 1) {
        flag = 1;
    } else {
        for (i = 2; i <= n / 2; i++) {
            if (n % i == 0) {
                flag = 1;
                break;
            }
        }
    }
    if (flag == 0)
        printf("prime\n");
    else
        printf("not prime\n");
    return 0;
}
Explanation: 1. Read an integer n from the user. 2. If n is less than or equal to 1, it is not prime. 3. Otherwise, loop from i = 2 to n/2. If n is divisible by any i, it is not prime. 4. If no divisor is found, n is prime. 5. Print the result accordingly.
Q95.Easy
Write a C program that reads a positive decimal integer from the user and prints its binary (base-2) representation. For example, if the user enters 13, the program should print 1101.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int bits[32], num, i;
    printf("Enter a decimal number: ");
    scanf("%d", &num);
    for (i = 0; num > 0; i++) {
        bits[i] = num % 2;
        num = num / 2;
    }
    printf("Binary of the given number is = ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", bits[i]);
    }
    printf("\n");
    return 0;
}
Explanation: 1) Read the decimal number into num. 2) Repeatedly take num % 2 to get the next binary digit (least significant first) and store it in an array bits[]. 3) Divide num by 2 each time; loop until num becomes 0. 4) The digits were stored in reverse order, so print the array from the last filled index down to 0. 5) Example: 13 -> remainders 1,0,1,1 stored, printed backwards gives 1101.
Q96.Easy
Write a C program that reads the number of rows from the user and prints a rhombus (parallelogram) star pattern: each row contains the given number of stars, and each successive row is shifted one space to the left, starting with the maximum indentation on the first row.
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int rows;
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    for (int i = rows; i >= 1; i--)
    {
        for (int j = 1; j <= i - 1; j++)
        {
            printf(" ");
        }
        for (int k = 1; k <= rows; k++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the number of rows into variable rows. 2) Outer loop i goes from rows down to 1, so the first line has the most leading spaces. 3) Inner loop j prints i-1 spaces, giving the left indentation for that line. 4) Inner loop k prints exactly rows stars, so every line has the same width. 5) Print a newline after each line; the decreasing indentation makes the block of stars look like a rhombus.
Q97.Easy
Write a C program that reads the number of rows from the user and prints a right-angled triangle of stars, where row 1 has one star, row 2 has two stars, and so on up to the given number of rows. Each star should be followed by a space.
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int rows;
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    for (int i = 1; i <= rows; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
Explanation: 1) Read the number of rows into variable rows. 2) Outer loop i runs from 1 to rows, one iteration per line. 3) Inner loop j runs from 1 to i, printing '* ' exactly i times on line i. 4) After the inner loop, print a newline to move to the next row. 5) So line 1 gets 1 star, line 2 gets 2 stars, and so on, forming a right triangle.
Q98.Easy
Write a C program to check whether a number is a palindrome. Input: 481 Output: not palindrome number. Input: 12321 Output: palindrome number.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int n, r, rev = 0, temp;
    printf("enter the number=");
    scanf("%d", &n);
    temp = n;
    while (n > 0)
    {
        r = n % 10;
        rev = (rev * 10) + r;
        n = n / 10;
    }
    if (temp == rev)
        printf("palindrome number");
    else
        printf("not palindrome number");
    return 0;
}
Explanation: 1) Read the number n and store a copy in temp. 2) Set rev = 0. Repeatedly take the last digit r = n % 10 and build rev = rev*10 + r, then drop the digit with n = n/10. 3) When n becomes 0, rev holds the reversed number. 4) Compare temp with rev: if equal print 'palindrome number', else print 'not palindrome number'. 5) Example: 481 reverses to 184, not equal, so output is 'not palindrome number'; 12321 reverses to 12321, so output is 'palindrome number'.
Q99.Easy
Write a C program that reads a 3-digit integer and checks whether it is an Armstrong number (a number equal to the sum of the cubes of its digits). For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int num, rem, sum = 0, temp;
    printf("Enter the number = ");
    scanf("%d", &num);
    temp = num;
    while(num > 0)
    {
        rem = num % 10;
        sum = sum + (rem * rem * rem);
        num = num / 10;
    }
    if(temp == sum)
        printf("Armstrong number");
    else
        printf("Not an Armstrong number");
    return 0;
}
Explanation: 1) Read num and store a copy in temp. 2) Initialise sum = 0. 3) While num > 0, take the last digit rem = num % 10. 4) Add rem*rem*rem (the cube of the digit) to sum. 5) Remove the last digit with num = num / 10. 6) After the loop, compare temp with sum: if equal print 'Armstrong number', else print 'Not an Armstrong number'. Example: 153 gives 1+125+27 = 153, so it is Armstrong.
Q100.Easy
Write a C program that reads an integer from the user and prints the sum of its digits. For example, if the user enters 4729, the program should print 22.
Show answer & explanation
Answer:
#include<stdio.h>
int main()
{
    int num, sum = 0, digit;
    printf("Enter a number: ");
    scanf("%d", &num);
    while(num > 0)
    {
        digit = num % 10;
        sum = sum + digit;
        num = num / 10;
    }
    printf("Sum is = %d", sum);
    return 0;
}
Explanation: 1) Read the integer num from the user. 2) Initialise sum = 0. 3) While num > 0, extract the last digit with digit = num % 10. 4) Add that digit to sum. 5) Remove the last digit with num = num / 10. 6) Repeat until num becomes 0, then print sum. For 4729: 9+2+7+4 = 22.
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