Determine Output: int counter (int value) { static int count =0; count = count +value; return count; } main() { int i , j; for (i=0; i <=5; i++) j = counter(i); printf("J = %d", j); return 0; }
-
5
-
4
-
10
-
15
The static variable count persists across function calls. The loop calls counter(0) through counter(5), accumulating: 0+1+2+3+4+5 = 15. The final value returned is 15.
To determine the output of the given code, let's go through it step by step:
We have a function named
counterthat takes an integervalueas input. Inside the function, there is a static variable namedcountthat is initialized to 0. The function adds the inputvalueto thecountvariable and returns the updated value ofcount.In the
mainfunction, we have two integer variablesiandjdeclared.There is a
forloop that iterates fromi = 0toi <= 5. In each iteration, thecounterfunction is called with the current value ofi, and the returned value is assigned toj.After the
forloop, the value ofjis printed usingprintf.
Let's track the value of j in each iteration of the for loop:
Iteration 1: i = 0
j = counter(0). The initial value ofcountis 0, andvalueis 0. The updated value ofcountis 0.- Therefore,
jis assigned the value of 0.
Iteration 2: i = 1
j = counter(1). The current value ofcountis 0, andvalueis 1. The updated value ofcountis 1.- Therefore,
jis assigned the value of 1.
Iteration 3: i = 2
j = counter(2). The current value ofcountis 1, andvalueis 2. The updated value ofcountis 3.- Therefore,
jis assigned the value of 3.
Iteration 4: i = 3
j = counter(3). The current value ofcountis 3, andvalueis 3. The updated value ofcountis 6.- Therefore,
jis assigned the value of 6.
Iteration 5: i = 4
j = counter(4). The current value ofcountis 6, andvalueis 4. The updated value ofcountis 10.- Therefore,
jis assigned the value of 10.
Iteration 6: i = 5
j = counter(5). The current value ofcountis 10, andvalueis 5. The updated value ofcountis 15.- Therefore,
jis assigned the value of 15.
After the for loop, the value of j is printed using printf. Therefore, the output of the code will be:
J = 15
So, the correct answer is D) 15.