What will be the output of the following program? int f (int x) { static int…
2018
What will be the output of the following program?
int f (int x)
{
static int y;
y += x;
return (y);
}
main ( )
{
int a, i;
for (i = 0; i < 6; i++)
a = f (i);
printf ("%d", a);
}
- A.
6
- B.
8
- C.
10
- D.
15
Attempted by 69 students.
Show answer & explanation
Correct answer: D
When i = 0:
f(0)is called.yis initialized to0.y += 0-> y = 0 + 0 = 0.f(0)returns0. Thus,a = 0.
When i = 1:
f(1)is called.yretains its previous value of0.y += 1-> y = 0 + 1 = 1.f(1)returns1. Thus,a = 1.
When i = 2:
f(2)is called.yretains its previous value of1.y += 2-> y = 1 + 2 = 3.f(2)returns3. Thus,a = 3.
When i = 3:
f(3)is called.yretains its previous value of3.y += 3-> y = 3 + 3 = 6.f(3)returns6. Thus,a = 6.
When i = 4:
f(4)is called.yretains its previous value of6.y += 4-> y = 6 + 4 = 10.f(4)returns10. Thus,a = 10.
When i = 5:
f(5)is called.yretains its previous value of10.y += 5-> y = 10 + 5 = 15.f(5)returns15. Thus,a = 15.
After this iteration, i becomes 6, the loop condition i < 6 becomes false, and the loop terminates.
Final Print Statement
The program executes printf ("%d", a);, which prints the final value stored in a.
The final value of a is 15.
Therefore, the correct option is 4) 15.