IAE Academy

GATE 2026 CS1 Q.63: solution and answer

GATE 2026 · CS1Q.63 · 2 marks · NAT

Consider the following program snippet. Assume that the program compiles and runs successfully. Further, assume that the fork() system call is always successful in creating a process.

int main () {
    int i;
    for (i = 0; i < 3; i++){
        if (fork() == 0){
            continue;
        }
        break;
    }
    printf("Hello!");
    return 0;
}

The total number of times that the printf statement gets executed is ________. (answer in integer)

See the question in the paper

Answer and solution

ANSWER

The printf statement is executed 4 times.

Official answer: 4Source: Official answer key, GATE 2026 CS1 (IIT Guwahati)

  1. fork() returns 0 in the child and a positive PID in the parent. The child runs continue and moves to the next iteration. The parent skips the if body, runs break, leaves the loop and reaches printf.

  2. Iteration : the original process forks . breaks out and prints (1 print). continues with .

  3. Iteration : forks . breaks out and prints (2 prints so far). continues with .

  4. Iteration : forks . breaks out and prints (3 prints so far). continues and becomes 3.

  5. For the condition is false, so it leaves the loop normally and prints (4 prints in total). forks nothing more.

  6. Only one process stays in the loop at each level, so the processes form a chain , not a tree. Each of the four processes reaches printf exactly once. Total prints (parents that break) (last child) .

KEY IDEA

Here the child continues the loop and the parent breaks out. So the processes form a chain, with one new process per iteration, instead of the doubling that happens when every process keeps looping. The count is the number of loop iterations plus the original process: .

WATCH OUT FOR

Treating this like the usual for loop with fork(), where the number of processes doubles each iteration, and answering . The break in the parent and the continue in the child stop the tree from growing.

From the GATE 2026 CS1 paper. Every question of this paper · Download the full paper · All 9 Processes & threads questions, with notes

More Processes & threads questions