MCQ Questions

Question Bank › Technical › C › MCQ

123456789

Bit Fields

Q1.Medium
What will be the output of this C program?
#include<stdio.h>
int main()
{
struct flags
{
int f:0;
}fl;
printf("%d", sizeof(fl));
return 0;
}
  1. 0
  2. 2
  3. Compilation Error
  4. 4
Show answer & explanation
Answer: (C) Compilation Error
Explanation: 1) A bit field's width must be greater than 0. 2) Here 'int f:0;' declares a zero-width bit field, which is not allowed. 3) The compiler reports an error for the invalid bit-field width. 4) Hence the program gives a compilation error.
Q2.MediumAnswer under review
What will be the output of the C program?
#include<stdio.h>
int main()
{
struct flags {
int f1: 2;
int f2: 9;
int f3: 6;
int f4: 1;
}fl;
printf("%d", sizeof(fl));
return 0;
}
  1. 2
  2. 3
  3. 4
  4. 0
Show answer & explanation
Answer: (B) 3
Explanation: 1. Total bits used = 2 + 9 + 6 + 1 = 18 bits. 2. 1 byte = 8 bits, so 18 bits need more than 2 bytes (16 bits). 3. The compiler allocates 3 bytes to hold 18 bits. 4. Output is 3.
Q3.MediumAnswer under review
What will be the output of this C program?
#include <stdio.h>
int main()
{
    struct flag
    {
        int bit : 1;
    };
    struct flag v = { 1 };
    printf("%d\n", v.bit);
    return 0;
}
  1. 1
  2. -1
  3. 0
  4. Error
Show answer & explanation
Answer: (A) 1
Explanation: 1. 'int bit : 1;' is a signed 1-bit field, so it can hold only 0 or -1 in two's complement. 2. The initializer { 1 } assigns the value 1 to the field. 3. The stored bit pattern is 1, which is read back as 1. 4. Hence printf prints 1.
Q4.Medium
Identify the error in this C program:
#include <stdio.h>
int main()
{
    struct flags
    {
        float ratio : 3;
    } f;
    printf("%d\n", sizeof(f));
    return 0;
}
  1. 4
  2. 3
  3. Error: a bit field cannot be declared with type float
  4. Error: invalid member access in structure
Show answer & explanation
Answer: (C) Error: a bit field cannot be declared with type float
Explanation: 1. A bit field's type must be an integer type (int, unsigned int, char, etc.) or an enumeration. 2. Floating-point types such as float and double are not allowed for bit fields. 3. Here 'float ratio : 3;' declares a bit field of type float, which the compiler rejects. 4. So the program produces a compile-time error: a bit field cannot be declared with type float.
Q5.Medium
Point out the error in the following program:
#include <stdio.h>
int main() {
    struct info {
        float rate: 5;
        char code: 4;
    };
    printf("size=%d", sizeof(struct info));
    return 0;
}
  1. Error: invalid structure member in printf
  2. Error in this float rate:5; statement
  3. No error
  4. None of above
Show answer & explanation
Answer: (B) Error in this float rate:5; statement
Explanation: 1. In C, bit fields can only be declared with type int, signed int, or unsigned int (and _Bool in C99). 2. The declaration 'float rate:5;' uses float, which is not allowed for bit fields. 3. The declaration 'char code:4;' is allowed because char is an integer type (implementation-defined signedness). 4. Therefore, the error is in the float bit-field declaration.
Q6.Medium
Bit fields CANNOT be used in a union.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: 1. In C, bit fields are allowed in both structures and unions. 2. For example, a union can have bit-field members: union U { unsigned int a:4; unsigned int b:4; int res; }; 3. This is valid and compiles without error. 4. Hence the statement is false.
Q7.Medium
What will be the output of the following program?
#include <stdio.h>
int main() {
    struct flags {
        int f1: 1;
        int f2: 4;
        int f3: 4;
    } f = {1, 2, 13};
    printf("%d, %d, %d\n", f.f1, f.f2, f.f3);
    return 0;
}
  1. 1, 2, 13
  2. 1, 4, 4
  3. -1, 2, -3
  4. -1, -2, -13
Show answer & explanation
Answer: (C) -1, 2, -3
Explanation: 1. In C, a bit-field declared as 'int' is signed by default. So the leftmost bit is the sign bit. 2. f1 is a 1-bit signed field. Storing 1 gives binary 1; as signed, this is -1 (two's complement). 3. f2 is a 4-bit signed field. Storing 2 gives 0010; sign bit 0, so value is +2. 4. f3 is a 4-bit signed field. Storing 13 gives 1101; sign bit 1, so it's negative. Two's complement of 1101 is 0011 = 3, so value is -3. 5. Hence output: -1, 2, -3.
Q8.Medium
What will be the output of the program on a 16-bit platform (Turbo C under DOS)? #include <stdio.h> int main() { struct flags { int f1:1; int f2:4; int f3:4; } bit; printf("%d\n", sizeof(bit)); return 0; }
  1. 1
  2. 2
  3. 4
  4. 9
Show answer & explanation
Answer: (B) 2
Explanation: 1. The bit fields total 1 + 4 + 4 = 9 bits. 2. On a 16-bit platform the storage unit for int is 2 bytes (16 bits). 3. 9 bits fit within one 16-bit unit, so the compiler allocates a single 2-byte unit. 4. Therefore sizeof(bit) = 2, and the output is 2.
Q9.Medium
What is the error in the following program on a 16-bit platform?
#include <stdio.h>
int main()
{
    struct flags
    {
        int a : 20;
    } f;
    printf("%d\n", sizeof(f));
    return 0;
}
  1. 20
  2. 2
  3. Error: Bit field too large
  4. Error: Invalid member access in structure
Show answer & explanation
Answer: (C) Error: Bit field too large
Explanation: 1. A bit field width cannot exceed the number of bits in its declared type. 2. Here the member is declared as int, which is 16 bits on a 16-bit platform. 3. The width specified is 20, which is greater than 16. 4. The compiler reports an error: bit field too large. 5. Hence the program gives a compilation error.
Q10.Medium
In C, is it allowed to declare an array of bit fields inside a structure?
  1. Yes, arrays of bit fields are allowed
  2. No, arrays of bit fields are not allowed
  3. Yes, but only with unsigned int
  4. Yes, but only inside a union
Show answer & explanation
Answer: (B) No, arrays of bit fields are not allowed
Explanation: 1. A bit field is declared as 'type name : width' inside a struct. 2. The C standard does not permit an array of bit fields, e.g. 'int flags[3] : 2;' is invalid. 3. You can have separate bit fields or a normal array of integers, but not an array of bit fields. 4. Hence the answer is No.

Bitwise Operators

Q11.Easy
The bitwise & operator can be combined with the ~ operator to switch off (clear) one or more chosen bits of a number.
  1. Yes
  2. No
Show answer & explanation
Answer: (A) Yes
Explanation: ~ creates a mask with 0s at the positions to clear and 1s elsewhere. ANDing the number with this mask (num & ~mask) leaves other bits unchanged and forces the chosen bits to 0. Example: 1011 & ~0010 = 1011 & 1101 = 1001, clearing bit 1.
Q12.Easy
In C, which bitwise operator is used to clear (turn off) a specific bit in a number while leaving the other bits unchanged?
  1. && operator
  2. & operator
  3. || operator
  4. ! operator
Show answer & explanation
Answer: (B) & operator
Explanation: 1) To turn off a chosen bit, you AND the number with a mask that has 0 at that bit position and 1 everywhere else. 2) The bitwise AND '&' performs this masking: x & ~(1<<k) clears bit k. 3) '&&' and '||' are logical operators, not bitwise. 4) '!' is logical NOT, also not bitwise. 5) Hence the correct choice is the '&' operator.
Q13.Easy
Bitwise operators can be used to reverse the sign of a number.
  1. Yes
  2. No
Show answer & explanation
Answer: (A) Yes
Explanation: 1. To reverse the sign of an integer in two's complement, you can use ~x + 1 (bitwise NOT then add 1). 2. For example, if x = 5 (00000101), ~x = 11111010, +1 = 11111011 which is -5. 3. Thus, bitwise operators can reverse the sign.
Q14.Easy
Bitwise operators can be used to generate a random number.
  1. Yes
  2. No
Show answer & explanation
Answer: (B) No
Explanation: Bitwise operators perform logical operations on individual bits (AND, OR, XOR, NOT, shifts). They are deterministic and do not introduce randomness. To generate random numbers, functions like rand() or srand() are used, often with a seed. Therefore, bitwise operators alone cannot generate random numbers.
Q15.Easy
The bitwise OR operator (|) can be used to multiply a number by a power of 2.
  1. Yes
  2. No
Show answer & explanation
Answer: (B) No
Explanation: Multiplying by a power of 2 is efficiently done using the left shift operator (<<). For example, x << 1 multiplies x by 2. The bitwise OR operator (|) performs a bitwise OR and does not perform multiplication. Therefore, the statement is false.
Q16.Easy
In C, which bitwise operator is used to test whether a specific bit in a number is set (1) or clear (0)?
  1. && operator
  2. & operator
  3. || operator
  4. ! operator
Show answer & explanation
Answer: (B) & operator
Explanation: The bitwise AND operator & compares each bit of two operands. To check if a particular bit is on, you AND the number with a mask that has only that bit set. If the result is non-zero, the bit is on; otherwise it is off. The logical operators &&, ||, and ! work on whole values, not individual bits.
Q17.Easy
The bitwise AND operator (&) can be used to check whether a particular bit in a number is set or not.
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1) To test bit k, AND the number with a mask that has only bit k set (1 << k). 2) If the result is non-zero, that bit is set; if zero, it is not set. 3) So bitwise & is indeed used for single-bit testing.
Q18.Easy
In C, the bitwise OR operator (|) can be used to set multiple bits in a number at once.
  1. Yes
  2. No
Show answer & explanation
Answer: (A) Yes
Explanation: By creating a mask with 1s in all the bit positions you want to set, you can OR the number with that mask to set multiple bits simultaneously. For example, to set bits 0 and 2, use x | 0b101. This sets those bits to 1 while leaving others unchanged. So the answer is Yes.
Q19.Easy
In C, bitwise AND (&) can be used to divide a number by powers of 2.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: Bitwise AND with a mask is used to clear or test bits, not to divide. Division by powers of 2 is typically done using right shift (>>) for unsigned integers. For example, x >> 1 divides by 2. Bitwise AND with (2^n - 1) gives the remainder modulo 2^n, not the quotient. So the statement is false.
Q20.Easy
In C, the bitwise OR operator (|) can be used to set a particular bit in a number.
  1. Yes
  2. No
Show answer & explanation
Answer: (A) Yes
Explanation: To set a bit at position k, you can OR the number with a mask that has 1 at that position (e.g., 1 << k). For example, to set the 3rd bit (0-indexed) of x, use x | (1 << 3). This leaves other bits unchanged and sets the target bit to 1. So the answer is Yes.
Q21.Easy
In C, left shifting an unsigned int or unsigned char by 1 is always equivalent to multiplying it by 2.
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: For unsigned integers, left shift by 1 (x << 1) multiplies the value by 2, provided there is no overflow. Since unsigned types have well-defined modulo 2^n arithmetic, the result is always 2*x modulo 2^n, which is the same as multiplication by 2. Thus the statement is true.
Q22.Easy
What will be the output of this C program?
#include<stdio.h>
int main()
{
int a = 16, b = 0x10, x, y, z;
x = a | b;
y = a & b;
z = x ^ y;
printf("%d, %d, %d, %d, %d\n", a, b, x, y, z);
return 0;
}
  1. 0, 0, 0, 0, 0
  2. 0, 16, 16, 16, 16
  3. 16, 16, 16, 16, 0
  4. 16, 16, 16, 16, 16
Show answer & explanation
Answer: (C) 16, 16, 16, 16, 0
Explanation: 1) a = 16 and b = 0x10 = 16, so both are 16. 2) x = a | b = 16 | 16 = 16. 3) y = a & b = 16 & 16 = 16. 4) z = x ^ y = 16 ^ 16 = 0 (same bits cancel). 5) Output: 16, 16, 16, 16, 0.
Q23.Easy
What will be the output of the following C program?
#include<stdio.h>
int main()
{
int y = 5;
(y & 1) ? printf("odd") : printf("even");
return 0;
}
  1. Compilation error
  2. odd
  3. even
  4. Runtime error
Show answer & explanation
Answer: (B) odd
Explanation: 1. y is 5, binary 0101. 2. y & 1 computes bitwise AND with 1 (0001): 0101 & 0001 = 0001, which is 1 (true). 3. The ternary operator evaluates the condition as true, so it executes printf("odd"). 4. Hence output is 'odd'.
Q24.Medium
In a C program on a system where unsigned int is 2 bytes (16 bits) wide, what is the output of the following program?

#include <stdio.h>
int main()
{
    unsigned int k = 32;
    printf("%x\n", ~k);
    return 0;
}
  1. ffdf
  2. 0020
  3. ffcf
  4. dfef
Show answer & explanation
Answer: (A) ffdf
Explanation: Step 1: k = 32 = 0x0020 in 16 bits (0000 0000 0010 0000). Step 2: ~k flips every bit: 1111 1111 1101 1111. Step 3: In hex that is 0xFFDF. Step 4: printf with %x prints ffdf (lowercase, no leading zeros beyond the value). So the output is ffdf.
Q25.Medium
What does the following C program print for the input 6?
#include<stdio.h>
int main()
{
unsigned int num;
int i;
scanf("%u", &num);
for(i=0; i<16; i++)
{
printf("%d", (num<<i & 1<<15)?1:0);
}
return 0;
}
  1. It prints all even bits of num
  2. It prints all odd bits of num
  3. It prints the 16-bit binary equivalent of num
  4. It gives a compilation error
Show answer & explanation
Answer: (C) It prints the 16-bit binary equivalent of num
Explanation: The mask 1<<15 checks the top bit after shifting num left by i. For i=0..15 this reads bits from MSB to LSB. Input 6 = 00000000 00000110, so the program prints 0000000000000110, i.e. the binary equivalent of num.
Q26.Medium
In the expression expression1 >> expression2, if expression1 is a signed integer with its leftmost bit set to 1, then on right shifting, the result will vary from computer to computer.
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1. Right shifting a signed negative integer (leftmost bit 1) is implementation-defined in C. 2. Some systems perform arithmetic shift (fill with sign bit), others logical shift (fill with 0). 3. Hence the result can vary across computers.
Q27.Medium
Assuming an integer is 2 bytes, what will be the output of the following program?
#include <stdio.h>
int main() {
    printf("%x\n", -2 << 2);
    return 0;
}
  1. fff8
  2. fff0
  3. 0
  4. -2
Show answer & explanation
Answer: (A) fff8
Explanation: 1. In 2-byte int, -2 is stored in 2's complement: binary of 2 is 00000000 00000010, 1's complement is 11111111 11111101, add 1 gives 11111111 11111110. 2. Left shift by 2: 11111111 11111110 << 2 = 11111111 11111000. 3. Convert binary 11111111 11111000 to hex: 1111 1111 1111 1000 = F F F 8. 4. So output is fff8.
Q28.Medium
What does the following program do?

#include <stdio.h>
int main() {
    unsigned int mask[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
    unsigned char num, i;
    scanf("%d", &num);
    for (i = 0; i <= 7; i++) {
        if (num & mask[i])
            printf("yes");
    }
    return 0;
}
  1. It will clear all bits that are set in the number num
  2. It will test whether each individual bit of num is set or clear
  3. It will set all bits that are clear in the number num
  4. It will produce a compilation error in the if statement
Show answer & explanation
Answer: (B) It will test whether each individual bit of num is set or clear
Explanation: 1. The array mask contains powers of two, each having exactly one bit set (bit 0 to bit 7). 2. The loop iterates i from 0 to 7. 3. In each iteration, num & mask[i] performs a bitwise AND. If the corresponding bit in num is 1, the result is non-zero (true), and "yes" is printed. 4. Thus, the program checks each bit of num from least significant to most significant and prints "yes" for each bit that is set. 5. Therefore, it tests whether the individual bits of num are ON or OFF.
Q29.Medium
If an unsigned int is 2 bytes wide, what will be the output of the following program?

#include <stdio.h>
int main() {
    unsigned int a = 0xabcd;
    ~a;
    printf("%x\n", a);
    return 0;
}
  1. abcd
  2. 0000
  3. 5432
  4. ffff
Show answer & explanation
Answer: (A) abcd
Explanation: 1. The variable a is initialized to 0xabcd. 2. The expression ~a computes the bitwise NOT, but the result is not stored anywhere. 3. Since a is not modified, it still holds 0xabcd. 4. printf prints the value of a in hexadecimal, which is abcd. 5. Therefore, the output is abcd.
Q30.MediumAnswer under review
The bitwise AND operator (&) alone can be used to check whether more than one bit in a number is on.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: 1) A single AND with a mask only tells you about the bits covered by that mask, giving one combined result. 2) To know whether MORE THAN ONE bit is on you must count the set bits (e.g. with a loop or Kernighan's trick), not just one AND. 3) Hence the statement is false.
Q31.Medium
What will be the output of the program?
#include<stdio.h>
int main()
{
unsigned char i = 0x40;
printf("%d\n", i << 1);
return 0;
}
  1. 0
  2. 128
  3. 64
  4. 40
Show answer & explanation
Answer: (B) 128
Explanation: 1) i is an unsigned char holding 0x40 = 64. 2) In the expression i << 1, i is promoted to int, so 64 << 1 = 128. 3) 128 fits in int, so printf("%d") prints 128.
Q32.MediumAnswer under review
What will be the output of the following C program?
#include <stdio.h>
int main() {
    printf("%d >> %d %d >> %d\n", 4 >> 1, 8 >> 1);
    return 0;
}
  1. 4 1 8 1
  2. 4 >> 1 8 >> 1
  3. 2 >> 4 Garbage value >> Garbage value
  4. 2 4
Show answer & explanation
Answer: (D) 2 4
Explanation: The printf format string is "%d >> %d %d >> %d\n", which expects four integer arguments. However, only two arguments are provided: 4 >> 1 and 8 >> 1. The first two format specifiers consume these arguments: 4 >> 1 = 2, and 8 >> 1 = 4. The remaining two %d specifiers have no corresponding arguments, leading to undefined behavior. In many implementations, they may print garbage values, but the first two outputs are 2 and 4. Among the options, only "2 4" correctly represents the first two printed numbers. Thus the answer is 2 4.
Q33.Medium
Assuming an integer is 2 bytes, what will be the output of the program?
#include<stdio.h>
int main()
{
    printf("%x\n", -3 << 2);
    return 0;
}
  1. fff4
  2. 0
  3. fffc
  4. Error
Show answer & explanation
Answer: (A) fff4
Explanation: Step 1: 3 in 16-bit binary is 00000000 00000011. Step 2: 1's complement is 11111111 11111100; adding 1 gives 2's complement of -3 = 11111111 11111101. Step 3: Left shift by 2 bits: 11111111 11110100. Step 4: In hexadecimal, 1111 1111 1111 0100 = fff4.
Q34.Medium
What will be the output of the following C program?
#include<stdio.h>
int main()
{
unsigned int num = -5;
printf("%d", ~num);
return 0;
}
  1. Compilation error
  2. 4
  3. 5
  4. some garbage value
Show answer & explanation
Answer: (B) 4
Explanation: 1. num is unsigned int initialized with -5, which wraps to 4294967291 (assuming 32-bit int). 2. ~num flips all bits: ~4294967291 = 4. 3. printf with %d prints the value as signed int, which is 4. 4. Hence output is 4.
Q35.Medium
What will be the output of the following program?
#include <stdio.h>
int main()
{
    int a = 6, b = 10;
    printf("%d, %d, %d\n", a|b&b|a, a|b&b|a, a^b);
    return 0;
}
  1. 14, 14, 12
  2. 110, 1, 12
  3. 62, 1, 12
  4. -64, 1, 12
Show answer & explanation
Answer: (A) 14, 14, 12
Explanation: 1. In C, & has higher precedence than |, so a|b&b|a is evaluated as a | (b&b) | a. 2. b&b = 10 & 10 = 10 (binary 1010). 3. a | 10 = 6 | 10 = 0110 | 1010 = 1110 = 14. 4. 14 | a = 14 | 6 = 1110 | 0110 = 1110 = 14. So first two values are 14, 14. 5. a^b = 6 ^ 10 = 0110 ^ 1010 = 1100 = 12. 6. Output: 14, 14, 12.

Comma Operator

Q36.Easy
What will be the output of the program?
#include<stdio.h>
int main()
{
    int i = 3;
    int j = i + (2, 4, 6, 8);
    printf("%d\n", j);
    return 0;
}
  1. 5
  2. 11
  3. 9
  4. 8
Show answer & explanation
Answer: (B) 11
Explanation: Step 1: The comma operator evaluates left to right and yields the rightmost value. Step 2: (2, 4, 6, 8) evaluates to 8. Step 3: j = 3 + 8 = 11. Step 4: Output is 11.
Q37.Easy
What will be the output of the following C program?
#include<stdio.h>
int main()
{
int b;
b = (4, 5, 6);
printf("%d", b);
return 0;
}
  1. 4
  2. 5
  3. 6
  4. Compilation error
Show answer & explanation
Answer: (C) 6
Explanation: 1. The comma operator evaluates each operand from left to right and yields the value of the rightmost operand. 2. Inside parentheses, (4, 5, 6) evaluates to 6. 3. So b is assigned 6. 4. printf prints 6.
Q38.Medium
What will be the output of this C program?
#include<stdio.h>
int main()
{
int x = 3;
if(x == (4, 3))
printf("Match");
else
printf("No Match");
return 0;
}
  1. Compilation Error
  2. Runtime Error
  3. Match
  4. No Match
Show answer & explanation
Answer: (C) Match
Explanation: 1. In (4, 3) the comma operator evaluates left to right and yields the last value, i.e. 3. 2. So the condition becomes x == 3. 3. Since x is 3, the condition is true. 4. The if block executes and prints 'Match'.
Q39.Medium
What will be the output of the following C program?
#include<stdio.h>
int main(){
int a = 10;
if(a == 5, 6)
printf("Yes");
else
printf("No");
return 0;
}
  1. Yes
  2. No
  3. Compilation Error
  4. None of the Above
Show answer & explanation
Answer: (A) Yes
Explanation: 1. The condition is if(a == 5, 6). The comma operator evaluates the left operand, discards it, then evaluates the right operand and returns its value. 2. So a == 5 is evaluated (result 0, since a=10), then discarded. 3. The value of the entire expression is 6, which is non-zero (true). 4. Therefore, the if block executes and prints "Yes".
Q40.Medium
What will be the output of the program?
#include<stdio.h>
int addmult(int ii, int jj)
{
    int kk, ll;
    kk = ii + jj;
    ll = ii * jj;
    return (kk, ll);
}
int main()
{
    int i = 5, j = 6, k, l;
    k = addmult(i, j);
    l = addmult(i, j);
    printf("%d, %d\n", k, l);
    return 0;
}
  1. 30, 30
  2. 11, 11
  3. 11, 30
  4. 30, 11
Show answer & explanation
Answer: (A) 30, 30
Explanation: 1) addmult(5,6): kk = 5+6 = 11, ll = 5*6 = 30. 2) return (kk, ll) uses the comma operator, which evaluates to the last value, ll = 30. 3) So k = 30; the same call gives l = 30. 4) printf prints 30, 30.

Command Line Arguments

Q41.Easy
What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample Pune Delhi Agra
/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
    int i;
    for(i = 1; i < argc; i++)
        printf("%s ", argv[i]);
    return 0;
}
  1. No output
  2. sample Pune Delhi Agra
  3. Pune Delhi Agra
  4. Error
Show answer & explanation
Answer: (C) Pune Delhi Agra
Explanation: argc = 4 (program name + 3 arguments). The loop starts at i = 1, so it skips argv[0] (the program name 'sample'). It prints argv[1]='Pune', argv[2]='Delhi', argv[3]='Agra', each followed by a space. Output: Pune Delhi Agra (program name not printed).
Q42.Easy
What will be the output of the program (myprog.c) given below if it is executed from the command line?
cmd> myprog red blue green
/* myprog.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
    int i;
    for(i = 1; i < argc; i++)
        printf("%c", argv[i][0]);
    return 0;
}
  1. rbg
  2. gbr
  3. rbg
  4. rgb
Show answer & explanation
Answer: (A) rbg
Explanation: argc = 4 (program name + 3 arguments). The loop runs for i = 1, 2, 3. argv[1] = "red", argv[1][0] = 'r'. argv[2] = "blue", argv[2][0] = 'b'. argv[3] = "green", argv[3][0] = 'g'. printf("%c") prints each first character with no space, giving 'rbg'.
Q43.Easy
A C program (prog.c) is compiled to an executable named prog. It is run three times from the command line as shown:
cmd> prog 5 6 7
cmd> prog 8 8 9
cmd> prog 10 11 12
/* prog.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
    printf("%s\n", argv[0]);
    return 0;
}
What will be printed each time the program runs?
  1. prog 10 11 12
  2. prog 5 6 7
  3. prog
  4. Error
Show answer & explanation
Answer: (C) prog
Explanation: argv[0] always holds the name of the program as it was invoked (the executable name), not the arguments. The arguments 5 6 7 (or 8 8 9 or 10 11 12) are stored in argv[1], argv[2], argv[3]. So printf("%s\n", argv[0]) prints just the program name 'prog' every time, regardless of the arguments passed. Hence the output is 'prog' in all three runs.
Q44.Easy
A program named calc.c is executed as: cmd > calc 4 5 6. The program is:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    int i, j = 0;
    for(i = 0; i < argc; i++)
        j = j + atoi(argv[i]);
    printf("%d\n", j);
    return 0;
}
What is the output?
  1. 456
  2. 15
  3. Error
  4. "456"
Show answer & explanation
Answer: (B) 15
Explanation: 1) argc = 4: argv[0]="calc", argv[1]="4", argv[2]="5", argv[3]="6". 2) atoi("calc") = 0, so j = 0. 3) j = 0 + 4 = 4; j = 4 + 5 = 9; j = 9 + 6 = 15. 4) Output: 15.
Q45.Easy
A C program named runme.c is compiled and executed from the command line as: cmd > runme 5 15 25. The program is:
#include <stdio.h>
int main(int argc, char *argv[])
{
    int i;
    for(i = 0; i < argc; i++)
        printf("%s\n", argv[i]);
    return 0;
}
What will be printed?
  1. 5 15 25
  2. runme 5 15
  3. runme 5 15 25
  4. 5 15
Show answer & explanation
Answer: (C) runme 5 15 25
Explanation: 1) argc counts the program name plus arguments: argc = 4. 2) argv[0] = "runme", argv[1] = "5", argv[2] = "15", argv[3] = "25". 3) The loop prints argv[0] through argv[3], each on its own line. 4) So the output is runme, 5, 15, 25 — i.e. 'runme 5 15 25'.
Q46.Medium
What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample kolkata chennai mumbai delhi
/* sample.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
    while(--argc > 0)
        printf("%s ", *++argv);
    return 0;
}
  1. sample kolkata chennai mumbai delhi
  2. kolkata chennai mumbai delhi
  3. kolkata chennai delhi
  4. chennai
Show answer & explanation
Answer: (B) kolkata chennai mumbai delhi
Explanation: Initially argc = 5 (program name + 4 arguments), argv points to argv[0]. Each iteration: --argc decrements count, and *++argv advances argv then prints the string it points to. Iteration 1: argc=4, argv->argv[1] prints 'kolkata'. Iteration 2: argc=3, argv->argv[2] prints 'chennai'. Iteration 3: argc=2, argv->argv[3] prints 'mumbai'. Iteration 4: argc=1, argv->argv[4] prints 'delhi'. Next --argc gives 0, loop stops. Output: kolkata chennai mumbai delhi (program name skipped).
Q47.Medium
A program myproc.c is compiled to myproc.exe and stored in the directory C:\TC. It is run from the DOS prompt as:
C:\TC>myproc
/* myproc.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
    printf("%s", argv[0]);
    return 0;
}
What will be the output?
  1. MYPROC.C
  2. C:\TC\MYPROC.EXE
  3. C:\TC
  4. Error
Show answer & explanation
Answer: (B) C:\TC\MYPROC.EXE
Explanation: argv[0] holds the full path/name used to launch the executable. When run from the DOS shell as C:\TC>myproc, the program name stored is the full path of the executable: C:\TC\MYPROC.EXE. printf("%s", argv[0]) therefore prints C:\TC\MYPROC.EXE. It is not the source file name (MYPROC.C) nor just the directory.
Q48.Medium
A program named prog.c is executed as: cmd > prog monday wednesday friday. The program is:
#include <stdio.h>
int main(int n, char *argv[])
{
    while(n)
        printf("%s ", argv[--n]);
    return 0;
}
What is the output?
  1. prog monday wednesday friday
  2. prog monday wednesday
  3. friday wednesday monday prog
  4. friday wednesday monday
Show answer & explanation
Answer: (C) friday wednesday monday prog
Explanation: 1) argc n = 4 (program name + 3 arguments). 2) argv[0]="prog", argv[1]="monday", argv[2]="wednesday", argv[3]="friday". 3) The loop pre-decrements: first prints argv[3]="friday", then argv[2]="wednesday", then argv[1]="monday", then argv[0]="prog". 4) So output is: friday wednesday monday prog.
Q49.Medium
A program named prog.c is executed as: cmd > prog monday wednesday friday. The program is:
#include <stdio.h>
int main(int argc, char *argv[])
{
    printf("%c", *++argv[2]);
    return 0;
}
What is the output?
  1. f
  2. m
  3. e
  4. r
Show answer & explanation
Answer: (C) e
Explanation: 1) argv[0]="prog", argv[1]="monday", argv[2]="wednesday", argv[3]="friday". 2) argv[2] points to 'w' of "wednesday". 3) ++argv[2] moves the pointer to the next character 'e'. 4) *++argv[2] dereferences it, giving 'e'. 5) Output: e.
Q50.Medium
Consider the program:
#include <stdio.h>
int main(int argc, char *argv[])
{
    printf("%d\n", argv[argc]);
    return 0;
}
If different command line arguments are supplied at different times, would the output of this program change?
  1. Yes
  2. No
Show answer & explanation
Answer: (B) No
Explanation: 1) argv[argc] is a special guaranteed element: the standard says argv[argc] is a null pointer. 2) So argv[argc] is always NULL regardless of how many arguments are passed. 3) Printing NULL with %d is undefined behaviour, but the value of the pointer itself does not depend on the arguments. 4) Hence the output does not change with different arguments — answer: No.
Q51.MediumAnswer under review
What will be the output of the program (sample.c) given below if it is executed from the command line?

cmd> sample monday wednesday saturday

/* sample.c */
#include <stdio.h>
int main(int argc, char *argv[]) {
    printf("%c", ++argv);
    return 0;
}
  1. s
  2. m
  3. sample
  4. monday
Show answer & explanation
Answer: (B) m
Explanation: 1. argv is a pointer to the array of argument strings; argv[0] = "sample", argv[1] = "monday", etc. 2. ++argv increments the pointer so it now points to argv[1], i.e., the string "monday". 3. printf with %c prints the first character of that string, which is 'm'. 4. So the output is m.
Q52.MediumAnswer under review
What will be the output of the program (myprog.c) given below if it is executed from the command line?

cmd> myprog monday wednesday saturday

/* myprog.c */
#include <stdio.h>
int main(int argc, char *argv[]) {
    printf("%c", *++argv[1]);
    return 0;
}
  1. e
  2. w
  3. m
  4. d
Show answer & explanation
Answer: (A) e
Explanation: 1. argv[0] = "myprog", argv[1] = "wednesday", argv[2] = "saturday". 2. argv[1] points to the first character 'w' of "wednesday". 3. ++argv[1] moves the pointer to the next character 'e'. 4. *++argv[1] dereferences it, giving 'e'. 5. So the output is e.

Command-line arguments

Q53.Easy
In C, every time we supply a new set of values at the command prompt to a program that reads command-line arguments, we must recompile the program.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: 1. Command-line arguments are supplied at run time, not at compile time. 2. The program reads them through argc and argv when it is executed. 3. Changing the values passed at the command prompt only changes the run-time input; the compiled executable stays the same. 4. Therefore no recompilation is needed, so the statement is False.
Q54.Easy
In C, the first argument supplied at the command line must always be the count of total arguments.
  1. True
  2. False
Show answer & explanation
Answer: (B) False
Explanation: 1) The first command-line token is the program name, not a count. 2) The count of arguments is computed by the system and passed to main as argc. 3) The user does not supply the count; it is automatic. 4) Hence the statement is False.
Q55.Medium
What will be the output of the program (run.c) given below if it is executed from the command line?
cmd> run red green blue
/* run.c */
#include<stdio.h>
int main(int argc, char *argv[])
{
    printf("%c\n", *++argv[1]);
    return 0;
}
  1. run red green blue
  2. run red
  3. e
  4. r
Show answer & explanation
Answer: (C) e
Explanation: 1. argv[0] = "run", argv[1] = "red", argv[2] = "green", argv[3] = "blue". 2. argv[1] points to the first character of "red", i.e. 'r'. 3. ++argv[1] increments the pointer so it now points to the second character, 'e'. 4. *++argv[1] dereferences that pointer, giving 'e'. 5. printf("%c\n", ...) prints e, so the output is 'e'.
Q56.MediumAnswer under review
What will be the output of the following C program when compiled with a standard compiler?
#include<stdio.h>
int main(int argc, char *argv[], char *envp[])
{
    int i;
    for(i=1; i<argc; i++)
        printf("%s\n", envp[i]);
    return 0;
}
  1. It prints the list of all environment variables
  2. It prints the list of all command-line arguments
  3. It prints the count of command-line arguments
  4. It gives a compile-time error because main() cannot have three parameters
Show answer & explanation
Answer: (A) It prints the list of all environment variables
Explanation: 1. main() here has three parameters: argc (argument count), argv (argument vector) and envp (environment pointer). 2. envp is an array of strings holding the environment variables of the process. 3. The loop runs from i=1 to i<argc-1, printing envp[i], i.e. entries of the environment list. 4. So the program prints environment variables (starting from the second one), not the command-line arguments. 5. Hence the correct description is 'List of all environment variables'.
Q57.Medium
In C, is there any way to make the command-line arguments available to other functions without passing them as parameters to those functions?
  1. Yes, using global variables such as _argc and _argv (compiler-dependent)
  2. No, they must always be passed explicitly
Show answer & explanation
Answer: (A) Yes, using global variables such as _argc and _argv (compiler-dependent)
Explanation: 1) main receives argc and argv as parameters. 2) Some compilers (e.g., Turbo C) also expose predefined global variables _argc and _argv holding the same values. 3) Other functions can read these globals without receiving parameters. 4) This is compiler-dependent (works in TC/TC++, not standard in gcc/Visual Studio), so the answer is Yes.
Q58.Medium
A C program named 'prog.c' is compiled to 'prog' and run on the command line as: cmd > prog. The source is:
/* prog.c */
#include <stdio.h>
int main(int argc, char *argv[])
{
    printf("%s\n", argv[argc-1]);
    return 0;
}
What will be printed?
  1. 0
  2. prog
  3. pro
  4. No output
Show answer & explanation
Answer: (B) prog
Explanation: 1) When run as 'prog' with no extra arguments, argc = 1 (program name only). 2) argv[0] = "prog", and argv[argc-1] = argv[0]. 3) printf prints argv[0], which is the program name 'prog'. 4) So the output is 'prog'.

Dynamic Memory

Q59.Easy
In C, which of the following is used to release memory that was allocated using malloc() or calloc()?
  1. remove(ptr);
  2. free(ptr);
  3. delete(ptr);
  4. dalloc(ptr);
Show answer & explanation
Answer: (B) free(ptr);
Explanation: 1) malloc()/calloc() allocate heap memory and return a pointer. 2) The matching deallocation function in C is free(). 3) delete is a C++ operator, not C. 4) remove() deletes a file, and dalloc() does not exist. 5) So free(ptr); is the correct statement.
Q60.MediumAnswer under review
What will be the output of the C program?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, marks[1];
marks[0] = 7;
free(marks);
printf("\nStored marks are ");
printf("\nmarks[%d] = %d ", 0, marks[0]);
return 0;
}
  1. 7
  2. 0
  3. Compilation error
  4. garbage value
Show answer & explanation
Answer: (D) garbage value
Explanation: 1) marks is a local array on the stack, not allocated by malloc/calloc. 2) free() may only be used on memory obtained from malloc/calloc/realloc; calling free(marks) is undefined behaviour. 3) The program compiles fine, so it is not a compilation error. 4) After the invalid free, reading marks[0] gives an unpredictable (garbage) value, not a guaranteed 7 or 0.
Q61.Medium
What will be the output of the program?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *q;
q = (int *)malloc(16); /* Assume q has address of 2048 */
free(q);
printf("%u", q);
return 0;
}
  1. 2048
  2. Garbage value
  3. 2052
  4. Random address
Show answer & explanation
Answer: (A) 2048
Explanation: 1. malloc(16) returns a block; assume the pointer q holds address 2048. 2. free(q) releases the memory but does NOT change the value stored in q. 3. So q still holds 2048. 4. printf("%u", q) prints that stored address value, i.e. 2048.

Dynamic Memory Allocation

Q62.Easy
In C, which standard library function is used to release memory that was previously allocated by malloc() or calloc()?
  1. release()
  2. free()
  3. delete()
  4. dealloc()
Show answer & explanation
Answer: (B) free()
Explanation: 1. malloc() and calloc() allocate memory on the heap. 2. That memory must be returned to the system when no longer needed. 3. The standard C function for this is free(). 4. delete() is C++ and release()/dealloc() are not standard C functions. 5. Hence free() is the correct answer.
Q63.Easy
In C, is it necessary to typecast the pointer returned by malloc() before assigning it to a pointer variable?
  1. Yes, a typecast is always required
  2. No, a typecast is not necessary
Show answer & explanation
Answer: (B) No, a typecast is not necessary
Explanation: 1. malloc() returns a void pointer (void *). 2. In C, a void pointer is implicitly converted to any other object pointer type. 3. So writing int *p = malloc(20); compiles without any cast. 4. Hence typecasting the result of malloc() is not necessary in C.
Q64.Easy
In C, malloc() returns a void pointer regardless of the data type for which memory is being allocated. Is this statement true or false?
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1. malloc() has prototype void *malloc(size_t size). 2. It returns a generic void pointer, not a typed pointer. 3. The programmer casts it to the required type, e.g. (float*)malloc(...). 4. Hence malloc() never returns a float pointer or double pointer by itself; the statement is True.
Q65.Easy
Which function should be used to release the memory that was allocated by calloc()?
  1. dealloc();
  2. malloc(variable_name, 0)
  3. free();
  4. memalloc(variable_name, 0)
Show answer & explanation
Answer: (C) free();
Explanation: 1. calloc() allocates memory from the heap. 2. Memory from calloc/malloc must be released with free(). 3. So the correct call is free(); passing the pointer to be freed.
Q66.Easy
In C, memory obtained using malloc() is allocated from the heap region, not from the stack.
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1. Local variables and function frames are placed on the stack. 2. malloc() requests memory at run time from the heap (free store). 3. Hence the statement is True.
Q67.Easy
Which pair of C library functions is used to dynamically allocate memory?
  1. malloc() and memalloc()
  2. alloc() and memalloc()
  3. malloc() and calloc()
  4. memalloc() and faralloc()
Show answer & explanation
Answer: (C) malloc() and calloc()
Explanation: 1. Dynamic memory in C is provided by the standard library <stdlib.h>. 2. malloc() allocates a single block of uninitialized memory of a given size. 3. calloc() allocates memory for an array of elements and initializes it to zero. 4. Functions like memalloc(), alloc() and faralloc() do not exist in standard C. 5. Hence the correct pair is malloc() and calloc().
Q68.Easy
How many bytes of memory does the following code request from malloc? #include<stdio.h> #include<stdlib.h> int main() { int *p; p = (int *) malloc ( 128 * 128 ); if (p == NULL) printf ( "Allocation failed" ); return 0 ; }
  1. 16384
  2. 128
  3. 256
  4. Allocation failed
Show answer & explanation
Answer: (A) 16384
Explanation: malloc is called with argument 128*128. 128*128 = 16384. So the code requests 16384 bytes.
Q69.Easy
Which single statement correctly combines these two statements?
char *q;
q = (char *) malloc(200);
  1. char q = *malloc(200);
  2. char *q = (char) malloc(200);
  3. char *q = (char*) malloc(200);
  4. char *q = (char *)(malloc *)(200);
Show answer & explanation
Answer: (C) char *q = (char*) malloc(200);
Explanation: 1. The declaration char *q; declares q as a pointer to char. 2. The assignment q = (char *) malloc(200); allocates 200 bytes and casts the void pointer to char *. 3. Combining them, we declare and initialize in one line: char *q = (char*) malloc(200); 4. The other options either drop the * on the declaration, cast wrongly, or use invalid syntax.
Q70.Medium
In a C program, a structure is defined as: struct student { int roll; float marks; char *name; }; A pointer 'st' of type struct student * is allocated memory using malloc(sizeof(struct student)), and then st->name is allocated 25 bytes using malloc(25). Which sequence correctly frees all the dynamically allocated memory without causing leaks or invalid access?
  1. free(st); then free(st->name);
  2. free(st->name); then free(st);
  3. free(st->name); only
  4. free(st); only
Show answer & explanation
Answer: (B) free(st->name); then free(st);
Explanation: Step 1: st->name points to a separate 25-byte block allocated by malloc. Step 2: st itself points to a separate block allocated by malloc. Step 3: Free the inner block first: free(st->name). Step 4: Then free the outer block: free(st). Step 5: Freeing st first would make st->name inaccessible (use-after-free), so order matters.
Q71.Medium
Assume integer is 2 bytes wide. How many bytes will be allocated for the following code? #include<stdio.h> #include<stdlib.h> #define MAXROW 3 #define MAXCOL 4 int main() { int (*p)[MAXCOL]; p = ( int (*) [MAXCOL]) malloc (MAXROW * sizeof (*p)); return 0 ; }
  1. 56 bytes
  2. 128 bytes
  3. 24 bytes
  4. 12 bytes
Show answer & explanation
Answer: (C) 24 bytes
Explanation: sizeof(*p) = size of array of MAXCOL=4 ints = 4*2 = 8 bytes. malloc allocates MAXROW * sizeof(*p) = 3 * 8 = 24 bytes.

Enums

Q72.Easy
What is the output of the program given below?
#include<stdio.h>
int main()
{
enum grade { gold, silver, bronze};
enum grade r1, r2, r3;
r1 = silver;
r2 = bronze;
r3 = gold;
printf("%d, %d, %d\n", r1, r2, r3);
return 0;
}
  1. 1, 2, 0
  2. 0, 1, 2
  3. 2, 1, 0
  4. 1, 0, 2
Show answer & explanation
Answer: (A) 1, 2, 0
Explanation: In an enum, the first member gets value 0, the next 1, and so on: gold=0, silver=1, bronze=2. r1 = silver = 1. r2 = bronze = 2. r3 = gold = 0. So printf prints 1, 2, 0.
Q73.Medium
Which one of the following is incorrect?
  1. enum colours = { red, green }c;
  2. enum colours{ red, green }c ;
  3. enum colours{ red, green };
  4. enum c{ red, green };
Show answer & explanation
Answer: (A) enum colours = { red, green }c;
Explanation: The correct syntax of an enum is: enum tag { list } variable; Option A writes 'enum colours = { red, green }c;' — an '=' sign is placed before the brace list, which is not allowed. Options B, C and D all follow the valid syntax (with or without a variable name). So option A is incorrect.
Q74.Medium
What will be the output of the program?
#include<stdio.h>
int main()
{
enum week {SUN=-1, MON, TUE=6, WED, THU, FRI};
printf("%d, %d, %d, %d, %d, %d\n", ++SUN, MON, TUE, WED, THU, FRI);
return 0;
}
  1. -1, 0, 1, 2, 3, 4
  2. Error
  3. 0, 1, 6, 3, 4, 5
  4. 0, 0, 6, 7, 8, 9
Show answer & explanation
Answer: (B) Error
Explanation: 1. Enum constants are integer constants, not modifiable variables. 2. The expression ++SUN tries to increment an enum constant. 3. The pre-increment operator requires a modifiable lvalue, but SUN is a constant. 4. Hence the compiler reports an error, so the program does not produce output.

File Handling

Q75.Easy
If an error occurs, what does the fseek() function return?
  1. NULL
  2. 0
  3. -1
  4. non-zero value
Show answer & explanation
Answer: (D) non-zero value
Explanation: The fseek() function returns 0 on success and a non-zero value on failure. Therefore, if an error occurs, it returns a non-zero value.
Q76.Easy
C supports which types of files?
  1. Low level Files
  2. High level Files
  3. Both a and b
  4. Executable Files only
Show answer & explanation
Answer: (C) Both a and b
Explanation: C supports both low-level file I/O (using system calls like open, read, write) and high-level file I/O (using standard library functions like fopen, fclose, fprintf, fscanf). Therefore, both low-level and high-level files are supported.
Q77.Easy
If the fopen() function is unable to open a file, what does it return?
  1. Compilation Error
  2. 0
  3. EOF
  4. NULL
Show answer & explanation
Answer: (D) NULL
Explanation: The fopen() function returns a FILE pointer. If it fails to open the file (e.g., file not found or permission denied), it returns a null pointer, which is represented by the macro NULL. It does not cause a compilation error, nor does it return 0 or EOF.
Q78.Easy
In C, what is the type of the FILE used for file operations?
  1. struct
  2. int
  3. char
  4. None of the above
Show answer & explanation
Answer: (A) struct
Explanation: In C, FILE is a predefined structure defined in the stdio.h header file. It is used to represent a file stream and contains information about the file. Therefore, FILE is a structure type.
Q79.Easy
What does the following program do?
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
int count=1;
fp = fopen("notes.txt", "r");
while((ch=getc(fp))!=EOF)
{
if(ch == '\n')
count++;
}
fclose(fp);
return 0;
}
  1. It counts the number of characters in the file
  2. It counts the number of words in the file
  3. It counts the number of blank lines in the file
  4. It counts the number of lines in the file
Show answer & explanation
Answer: (D) It counts the number of lines in the file
Explanation: Step 1: getc reads one character at a time until EOF. Step 2: count starts at 1 (assuming at least one line). Step 3: Every time a newline '\n' is seen, count is incremented — each newline marks the end of a line. Step 4: So count ends up equal to the number of lines in the file.
Q80.Easy
In C, FILE is a structure type that is typedef'd in the stdio.h header file.
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1. stdio.h defines FILE as a typedef for a structure holding stream information (file descriptor, buffer pointer, position, error/EOF indicators). 2. Programs use FILE * pointers for file operations. 3. Hence the statement that FILE is a structure typedef'd in stdio.h is correct.
Q81.Medium
What will be the output of the C program?
/*This program uses two files*/
#include<stdio.h>
int main()
{
char ch;
FILE *fptr1, *fptr2;
fptr1 = fopen("notes1.txt", "w");
fptr2 = fopen("notes2.txt", "w");
printf("Thank you.");
fclose(fptr1, fptr2);
return 0;
}
  1. Thank you.
  2. Prints nothing
  3. Compilation error
  4. None of the above
Show answer & explanation
Answer: (C) Compilation error
Explanation: 1. fclose() takes exactly one argument of type FILE*. 2. The call fclose(fptr1, fptr2) passes two arguments. 3. The compiler reports: too many arguments to function 'fclose'. 4. Hence the program does not compile and gives a compilation error.
Q82.Medium
What will be the output of the C program?
/*attempting to open an existing file for reading and writing*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char city[40], city1[40];
fptr = fopen("cities.txt", "r+");
if(fptr == NULL)
{
printf("File not exist");
exit(1);
}
printf("Enter your city: ");
gets(city);
fputs(city, fptr);
rewind(fptr);
fgets(city1, 40, fptr);
printf("City: %s", city1);
fclose(fptr);
return 0;
}
/*assume the file cities.txt does not exist and you type a city name*/
  1. File not exist
  2. City: Mumbai
  3. City: Mumbai garbage value
  4. Compilation Error
Show answer & explanation
Answer: (A) File not exist
Explanation: 1. The file is opened with mode "r+", which only allows reading and writing an already existing file. 2. Mode "r+" does NOT create a new file if it is missing. 3. Since cities.txt does not exist, fopen() returns NULL and fptr becomes NULL. 4. The if condition (fptr == NULL) is true, so it prints "File not exist" and exits. 5. Hence the output is: File not exist.
Q83.Medium
What will be the output of the C program?
/*The file notes.txt already exists.*/
/*This program uses notes.txt which contains the following data*/
/* Hello. This is examprep.in. */
#include<stdio.h>
int main()
{
char ch;
FILE *fptr;
fptr = fopen("notes.txt", "w+");
fclose(fptr);
fptr = fopen("notes.txt", "r");
while((ch = fgetc(fptr))!= EOF)
{
printf("%c",ch);
}
fclose(fptr);
return 0;
}
  1. Hello
  2. Garbage values
  3. Compilation Error
  4. Nothing will be displayed
Show answer & explanation
Answer: (D) Nothing will be displayed
Explanation: 1. "w+" opens the file for reading and writing and truncates it to zero length if it already exists. 2. The program opens notes.txt in "w+" mode and immediately closes it, so all existing data is erased. 3. Reopening in "r" mode finds an empty file, so fgetc returns EOF at once. 4. The while loop never prints anything — nothing is displayed.
Q84.MediumAnswer under review
What will be the output of the C program?
/*The file notes.txt already exists.*/
/*This program uses notes.txt which contains the following data*/
/*Hello. This is examprep.in.*/
#include<stdio.h>
int main()
{
char str[50];
FILE *fptr;
fptr = fopen("notes.txt", "r");
fgets(str, 18, fptr);
printf("%s", str);
return 0;
}
  1. Hello. This is examprep.in
  2. Hello. This is exa
  3. Hello. This is exam
  4. Garbage Values
Show answer & explanation
Answer: (B) Hello. This is exa
Explanation: 1. fgets(str, n, fptr) reads at most n-1 characters and then adds a null terminator. 2. Here n = 18, so it reads at most 17 characters from the start of the file. 3. The first 17 characters of "Hello. This is examprep.in." are "Hello. This is exa". 4. printf prints that string, giving "Hello. This is exa".
Q85.Medium
What will be the output of the C program?
/*This program uses the file "scores.txt"*/
/*7 8 9 6*/
#include<stdio.h>
int main()
{
int num[4];
int i = 0, tot = 0;
FILE *fptr;
fptr = fopen("scores.txt", "r");
if(fptr == NULL)
{
printf("File not exist");
}
for(i = 0; i < 4; i++)
{
fscanf(fptr, "%d,", &num[i]);
}
for(i = 0; i < 4; i++)
{
printf("%d ", num[i]);
tot = tot + num[i];
}
printf("tot = %d", tot);
fclose(fptr);
return 0;
}
  1. Compilation Error
  2. 7 8 9 tot = 24
  3. 7 8 9 6
  4. 7 8 9 6 tot = 30
Show answer & explanation
Answer: (D) 7 8 9 6 tot = 30
Explanation: 1. fopen opens scores.txt for reading. 2. fscanf with "%d," reads each integer; the trailing comma in the format is just a literal that matches (or is skipped) between numbers. 3. The four values 7, 8, 9, 6 are stored in num[0..3]. 4. The second loop prints each value followed by a space: "7 8 9 6 ". 5. tot = 7+8+9+6 = 30, so it prints "tot = 30".
Q86.MediumAnswer under review
What will be the output of the C program?
/*This program uses the file "marks.txt"*/
/*10.5 20.5 30.5 40.5*/
#include<stdio.h>
int main()
{
float marks[4];
float i = 0, tot = 0;
FILE *fptr;
fptr = fopen("marks.txt", "r");
if(fptr == NULL)
{
printf("File not exist");
}
fclose(fptr);
for(i = 0; i < 4; i++)
{
fscanf(fptr, "%f", &marks[i]);
}
for(i = 0; i < 4; i++)
{
tot = tot + marks[i];
}
printf("tot = %f", tot);
return 0;
}
  1. 102.000000
  2. sum of garbage values
  3. Compilation Error
  4. Runtime Error
Show answer & explanation
Answer: (B) sum of garbage values
Explanation: 1. The file is opened with fopen and then immediately closed with fclose before any reading. 2. The loop calls fscanf on a closed file pointer, which fails and leaves the array elements uninitialized (garbage). 3. Adding garbage values gives a garbage total, so the printed sum is unpredictable garbage.
Q87.Medium
What will be the output of the C program?
/*This program uses the file "marks1.txt"*/
/*The file contains: 2.5, 3.5, 4.5, 5.5 (comma separated)*/
#include<stdio.h>
int main()
{
float num[4];
float i = 0, tot = 0;
FILE *fptr;
fptr = fopen("marks1.txt", "r");
if(fptr == NULL)
{
printf("File not exist");
}
fclose(fptr);
for(i = 0; i < 4; i++)
{
fscanf(fptr, "%f", &num[i]);
}
for(i = 0; i < 4; i++)
{
tot = tot + num[i];
}
printf("tot = %f", tot);
return 0;
}
  1. 16.000000
  2. 16.500000
  3. Null or Unexpected Result
  4. Compilation Error
Show answer & explanation
Answer: (C) Null or Unexpected Result
Explanation: 1) The file is closed with fclose(fptr) BEFORE the fscanf loop runs, so the stream is no longer valid. 2) Reading from a closed file pointer is undefined behaviour, so the program does not produce a reliable sum. 3) Also the values are comma separated, so plain "%f" would stop at the comma anyway. 4) Hence the output is unexpected/null rather than a clean total.
Q88.Medium
What will be the content of the file 'log.c' after this program runs?
#include<stdio.h>
int main()
{
FILE *fp1, *fp2;
fp1 = fopen("log.c", "w");
fp2 = fopen("log.c", "w");
fputc('X', fp1);
fputc('Y', fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
  1. Y
  2. X Y
  3. Y Y
  4. Error in opening file 'log.c'
Show answer & explanation
Answer: (A) Y
Explanation: Step 1: Both fopen calls use mode "w", which truncates the file each time it is opened. Step 2: fputc('X', fp1) writes X, but fp2 was opened later in write mode and its buffer/position governs the file. Step 3: fputc('Y', fp2) writes Y, overwriting the earlier content. Step 4: After closing, the file contains only 'Y'.
Q89.Medium
A file contains the line "We are going home\r\n". If this line is read into the array str using fgets(str, 100, fp), what will str contain?
  1. "We are going home\r\n\0"
  2. "We are going home\r\0"
  3. "We are going home\n\0"
  4. "We are going home"
Show answer & explanation
Answer: (C) "We are going home\n\0"
Explanation: Step 1: fgets reads characters until it hits a newline or n-1 characters. Step 2: On a text-mode stream, the '\r\n' pair is translated to a single '\n'. Step 3: fgets stops after storing that '\n' and appends a '\0' terminator. Step 4: So str holds "We are going home\n\0".
Q90.Medium
Identify the error in this C program:
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned char;
FILE *fp;
fp=fopen("data.txt", "r");
if(!fp)
{
printf("Cannot open file");
exit(1);
}
fclose(fp);
return 0;
}
  1. Error: the statement 'unsigned char;' is invalid
  2. Error: unknown file pointer
  3. No error
  4. None of the above
Show answer & explanation
Answer: (A) Error: the statement 'unsigned char;' is invalid
Explanation: Step 1: Look at the declaration 'unsigned char;' — it declares a type but gives no variable name. Step 2: In C every declaration must name at least one variable (or be a valid abstract declaration), so this line is a syntax error. Step 3: The rest of the program (fopen, check, fclose) is fine. Step 4: Hence the error is in the 'unsigned char;' statement.
Q91.Medium
What does the following C program do?
#include<stdio.h>
#include<string.h>
int main()
{
    FILE *fp;
    char word[21], ch;
    int i = 0;
    fp = fopen("NOTES.TXT", "r");
    while((ch = getc(fp)) != EOF)
    {
        if(ch == '\n' || ch == ' ')
        {
            word[i] = '\0';
            strrev(word);
            printf("%s ", word);
            i = 0;
        }
        else
            word[i++] = ch;
    }
    fclose(fp);
    return 0;
}
  1. It writes some text into a file
  2. It reads a text file and prints each word in reverse order
  3. It writes text into a file in reverse order
  4. It deletes the contents of the file
Show answer & explanation
Answer: (B) It reads a text file and prints each word in reverse order
Explanation: 1. fopen("NOTES.TXT","r") opens the file for reading. 2. getc reads characters one by one into word[] until a space or newline is found. 3. On hitting a space/newline, word is null-terminated and strrev reverses it, then printf prints the reversed word. 4. i is reset to 0 so the next word is collected fresh. 5. So the program reads the file and displays each word reversed.
Q92.Hard
What will be the output of the C program?
/*The file notes.txt already exists.*/
/*This program uses notes.txt which contains the following data*/
/*Hello. This is examprep.in.*/
#include<stdio.h>
int main()
{
char ch;
FILE *fptr;
fptr = fopen("notes.txt", "r+");
fprintf(fptr, "Greetings. ");
fclose(fptr);
fptr = fopen("notes.txt", "r");
while((ch = fgetc(fptr))!= EOF)
{
printf("%c",ch);
}
fclose(fptr);
return 0;
}
  1. Greetings.
  2. Greetings. Hello. This is examprep.in.
  3. Greetings. is examprep.in.
  4. None of the above
Show answer & explanation
Answer: (C) Greetings. is examprep.in.
Explanation: 1. "r+" opens the existing file for reading and writing, with the file position at the start. 2. fprintf writes "Greetings. " (11 characters) over the first 11 characters of the file, overwriting them in place. 3. Original: "Hello. This is examprep.in." — first 11 chars "Hello. This" are replaced by "Greetings. ". 4. Remaining text after position 11 is " is examprep.in.". 5. Reading the whole file gives "Greetings. is examprep.in.".

File I/O Functions

Q93.Easy
Can fprintf() be used to display output on the screen in C?
  1. Yes
  2. No
Show answer & explanation
Answer: (A) Yes
Explanation: 1. fprintf() writes formatted output to any stream given as its first argument. 2. The screen is represented by the standard output stream stdout. 3. So fprintf(stdout, "%s %d", name, marks); prints to the screen, just like printf. 4. Therefore the answer is Yes.
Q94.Medium
In C, under which conditions does the getc() function return EOF?
  1. It never returns EOF
  2. When the end of the file is reached
  3. When getc() fails to read a character
  4. Both when end of file is reached and when getc() fails to read a character
Show answer & explanation
Answer: (D) Both when end of file is reached and when getc() fails to read a character
Explanation: 1. getc() reads one character from a stream. 2. If the file pointer is at end-of-file, it returns EOF. 3. If a read error occurs (it fails to read), it also returns EOF. 4. Therefore both situations give EOF, so the combined option is correct.
Q95.Medium
In C, which statement correctly describes the behaviour of the fflush() function?
  1. It flushes all streams when passed NULL, and flushes only the specified stream when a stream pointer is passed.
  2. It can flush only a single specified stream, never all streams at once.
  3. It clears the input/output buffer contents but cannot be applied to output streams.
  4. It flushes only file buffers opened in binary mode.
Show answer & explanation
Answer: (A) It flushes all streams when passed NULL, and flushes only the specified stream when a stream pointer is passed.
Explanation: 1) fflush() writes any buffered output of a stream to its file. 2) When called as fflush(fp), only the stream fp is flushed. 3) When called as fflush(NULL), all open output streams are flushed. 4) Hence it can flush a specified stream or all streams, matching option A.

Function Pointers

Q96.Medium
Point out the error, if any, in the following program.
#include <stdio.h>
void display(int (*ff)());
int main()
{
    int show();
    int (*f)();
    f = show;
    display(f);
    return 0;
}
void display(int (*ff)())
{
    (*ff)();
}
int show()
{
    printf("Bharat");
}
  1. Error: invalid parameter in function display()
  2. Error: invalid function call f = show;
  3. No error and prints "Bharat"
  4. No error and prints nothing.
Show answer & explanation
Answer: (C) No error and prints "Bharat"
Explanation: 1) show is a function returning int; int (*f)() is a pointer to such a function, so f = show; is valid. 2) display takes int (*ff)() — the same pointer type — so passing f is valid. 3) Inside display, (*ff)() calls the function pointed to, i.e. show. 4) show prints "Bharat" and returns an int (implicitly 0), which is fine. 5) So the program compiles and prints "Bharat".
Q97.Medium
Is the following declaration correct in C?
void (*f)(int, void(*)());
  1. Yes
  2. No
Show answer & explanation
Answer: (A) Yes
Explanation: 1) Read from inside out: (*f) means f is a pointer. 2) The outer (int, void(*)()) is its parameter list: an int and a pointer to a function taking no arguments and returning void. 3) The leading void is the return type of the function f points to. 4) So f is a pointer to a function returning void and taking (int, pointer-to-function). This is a valid declaration.
Q98.Medium
What will be the output of the following C program?
#include <stdio.h>
int check(int, int);
typedef int (*fp)(int, int);
int apply(fp, int, int);
int main()
{
    printf("%d\n", apply(check, 8, 8));
    return 0;
}
int check(int a, int b)
{
    return (a == b);
}
int apply(fp f, int a, int b)
{
    return ((*f)(a, b));
}
  1. 8
  2. 1
  3. 0
  4. -1
Show answer & explanation
Answer: (B) 1
Explanation: Step 1: apply receives the function pointer f pointing to check, with a = 8, b = 8. Step 2: (*f)(8, 8) calls check(8, 8). Step 3: check returns (8 == 8) which is 1. Step 4: printf prints 1.
Q99.Medium
What will be the output of this C program?

#include <stdio.h>
int run(int (*)());
int main() {
    run(main);
    printf("Bye\n");
    return 0;
}
int run(int (*p)()) {
    printf("Welcome ");
    return 0;
}
  1. Infinite loop
  2. Bye
  3. Welcome Bye
  4. Error
Show answer & explanation
Answer: (C) Welcome Bye
Explanation: Step 1: main calls run(main), passing the address of main as a function pointer. Step 2: run prints "Welcome " and returns 0; it never calls p, so no recursion. Step 3: Control returns to main, which prints "Bye". Step 4: Output is "Welcome Bye".

Functions

Q100.Easy
In C, can a function return a floating point number (for example, a value of type float or double)?
  1. True
  2. False
Show answer & explanation
Answer: (A) True
Explanation: 1) A C function's return type can be any valid data type, including float and double. 2) Example: double area(double r) { return 3.14 * r * r; } returns a floating point value. 3) Hence the statement is True.
123456789

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