+ 1
Array passed to function code
Can someone explain for my understanding how the output of code is 14? I tested the code using VS2019 as well as the current CodeBlock. The output corresponds to the quiz answer. This is a quiz code submitted by Swapnil #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, 5}; printf(“%d”, f(a, 3)); }
1 Réponse
+ 3
Just keep a track of all recursion calls:-
f(a,3)
The condition in else if is satisfied (as 12%2=0)
now return 12+f(7,2)
Now the condition in else is evaluated
Return 12+(7-f(5,1))
Now again else condition will be true
Return 12+(7-(5-f(a,3))
Now the base condition is satisfied and function returns 0 so our final expression is
12+7-5=14