IAE Academy

GATE 2024 CS1 Q.18: solution and answer

GATE 2024 · CS1Q.18 · 1 mark · MCQ

Consider the following C program:

#include <stdio.h>
int main(){
    int a = 6;
    int b = 0;
    while(a < 10) {
        a = a / 12 + 1;
        a += b;}
    printf("%d", a);
    return 0;}

Which one of the following statements is CORRECT?

  1. (A)

    The program prints 9 as output

  2. (B)

    The program prints 10 as output

  3. (C)

    The program gets stuck in an infinite loop

  4. (D)

    The program prints 6 as output

See the question in the paper

Answer and solution

ANSWER

The program gets stuck in an infinite loop.

Official answer: CSource: Official answer key, GATE 2024 CS1 (IISc Bengaluru)

  1. Initial state: a = 6, b = 0 (b is never modified anywhere in the program).

  2. Check loop condition: a < 10, i.e. 6 < 10, true — enter the loop body.

  3. Evaluate a = a / 12 + 1: with int division (truncation toward zero, both operands non-negative), 6 / 12 = 0, so a = 0 + 1 = 1.

  4. Evaluate a += b: b = 0, so a stays 1.

  5. Recheck loop condition: a = 1 < 10, true — enter the loop body again.

  6. Evaluate a = a / 12 + 1: 1 / 12 = 0 (int division), so a = 0 + 1 = 1.

  7. Evaluate a += b: b is still 0, so a stays 1.

  8. From this point the state (a = 1, b = 0) exactly recreates itself every iteration: a is reset to 1 by the assignment and b never changes, so a can never reach 10 and the while condition never becomes false. The program is stuck in an infinite loop and never reaches the printf statement.

KEY IDEA

Integer division truncates toward zero in C, so once a becomes small (≤ 11), a / 12 always evaluates to 0 and a collapses to the fixed point 1; since b is never modified, the loop state never changes and the loop cannot terminate.

WATCH OUT FOR

Assuming a will eventually grow toward 10 because of the += b step, without noticing that b is initialized to 0 and never updated anywhere in the program, so it contributes nothing and a is permanently trapped at 1 after the first iteration.

From the GATE 2024 CS1 paper. Every question of this paper · Download the full paper · All 7 C basics questions, with notes

More C basics questions