+ 3

Why this code prints: 14

#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 ("%i", f(a,3)); return 0; }

1st Feb 2019, 1:20 PM
Mihai C
Mihai C - avatar
3 ответов
+ 9
12+(7-(5-0)) 14 ------------------------------------------------------------------------- 12%2 ==0 12 + f(a+1 , 2) | 7%2!=0 7- f(a+1 , 1) | 5%2!=0 5-f(a+1,0) | n==0 // base condition satisfied
1st Feb 2019, 1:47 PM
Rstar
Rstar - avatar
+ 2
You have to track the recursion. In each call of f(a+1,n-1), we move the pointer to the right and decrease n. f(a,3) will lead to the return in the else if branch, since 12%2 == 0. We add 12 + .... And call f(a+1,2), the check 7%2 is wrong (no even number), so we get in the else branch. We substract 12 + (7 - ...) And call f(a+1,1). Again 5 is odd, therefore we are in the else branch again. 12 + (7 - (5 - ...)) Now, for the call f(a+1,0) we get to the base case, which returns zero. So we finally have 12 + ( 7 - (5 - 0)) = 12+7-5 = 14 I think some compilers will throw an error, since we move the pointer out of the array. On the other hand, we do not access this address. So I'm not quite sure, maybe it works for all compilers.
1st Feb 2019, 1:47 PM
Matthias
Matthias - avatar
0
14
2nd Feb 2019, 1:53 AM
M3TA