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?
View worked solution
Answer: B
The function r() uses a static variable num initialized to . The post-decrement operator num-- returns the current value of num and then decrements it by .
Let's trace the execution of the for loop step-by-step:
- Initialization:
r()is called.- Returns (ignored).
numbecomes .
- First Iteration:
- Condition:
r()is evaluated. Returns (non-zero, sotrue).numbecomes . - Body:
printf("%d", r())is executed.r()returns andnumbecomes . This prints5. - Increment:
r()is called. Returns .numbecomes .
- Condition:
- Second Iteration:
- Condition:
r()is evaluated. Returns (non-zero, sotrue).numbecomes . - Body:
printf("%d", r())is executed.r()returns andnumbecomes . This prints2. - Increment:
r()is called. Returns .numbecomes .
- Condition:
- Third Iteration:
- Condition:
r()is evaluated. Returns (zero, sofalse).numbecomes . - The loop terminates.
- Condition:
The printed output is 52, which corresponds to option B.
Free practice · Your answers on this page are not saved.
