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);

}

  1. A.

    6

  2. B.

    8

  3. C.

    10

  4. D.

    15

Attempted by 69 students.

Show answer & explanation

Correct answer: D

  • When i = 0:

    • f(0) is called.

    • y is initialized to 0.

    • y += 0 -> y = 0 + 0 = 0.

    • f(0) returns 0. Thus, a = 0.

  • When i = 1:

    • f(1) is called. y retains its previous value of 0.

    • y += 1 -> y = 0 + 1 = 1.

    • f(1) returns 1. Thus, a = 1.

  • When i = 2:

    • f(2) is called. y retains its previous value of 1.

    • y += 2 -> y = 1 + 2 = 3.

    • f(2) returns 3. Thus, a = 3.

  • When i = 3:

    • f(3) is called. y retains its previous value of 3.

    • y += 3 -> y = 3 + 3 = 6.

    • f(3) returns 6. Thus, a = 6.

  • When i = 4:

    • f(4) is called. y retains its previous value of 6.

    • y += 4 -> y = 6 + 4 = 10.

    • f(4) returns 10. Thus, a = 10.

  • When i = 5:

    • f(5) is called. y retains its previous value of 10.

    • y += 5 -> y = 10 + 5 = 15.

    • f(5) returns 15. 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.

Explore the full course: Up Lt Grade Assistant Teacher 2025