Consider the following C program: #include <stdio.h> int r(){ static int…

2019

Consider the following C program:

#include <stdio.h>
int r(){
    static int num=7;
    return num--;
}

int main(){
    for (r();r();r())
         printf(“%d”,r());
    return 0;
}

Which one of the following values will be displayed on execution of the programs?

  1. A.

    41

  2. B.

    52

  3. C.

    63

  4. D.

    630

Attempted by 200 students.

Show answer & explanation

Correct answer: B

Key idea: the function returns the current value of a static variable and then decrements it (post-decrement). Each call updates the same static variable sequentially.

  • Initial static num = 7.

  • Initialization call r() returns 7, then num becomes 6.

  • Condition call r() returns 6 (nonzero), then num becomes 5 — loop enters.

  • printf's call r() returns 5 (printed first digit), then num becomes 4.

  • Increment call r() returns 4, then num becomes 3.

  • Next condition call r() returns 3 (nonzero), then num becomes 2 — second iteration begins.

  • printf's call r() returns 2 (printed second digit), then num becomes 1.

  • Increment call r() returns 1, then num becomes 0.

  • Next condition call r() returns 0 (loop stops), then num becomes -1.

Result: the program prints 52.

Common pitfall: confusing pre-decrement with post-decrement or misordering the sequence of function calls in the for loop. Trace each call in order to avoid mistakes.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir