What is the value printed by the following C program? #include<stdio.h> int…
2010
What is the value printed by the following C program?
#include<stdio.h>
int f(int *a, int n)
{
if (n <= 0) return 0;
else if (*a % 2 == 0) return *a+f(a+1, n-1);
else return *a - f(a+1, n-1);
}
int main()
{
int a[] = {12, 7, 13, 4, 11, 6};
printf("%d", f(a, 6));
return 0;
}
- A.
-9
- B.
5
- C.
15
- D.
19
Attempted by 53 students.
Show answer & explanation
Correct answer: C
Answer: 15
Reasoning: The function processes each array element recursively, adding the element when it is even and subtracting the result of the recursive call when the element is odd. Evaluate from the last element upward:
Element 6 (value 6, even): f = 6 + 0 = 6
Element 5 (value 11, odd): f = 11 - 6 = 5
Element 4 (value 4, even): f = 4 + 5 = 9
Element 3 (value 13, odd): f = 13 - 9 = 4
Element 2 (value 7, odd): f = 7 - 4 = 3
Element 1 (value 12, even): f = 12 + 3 = 15
Therefore, the program prints 15.