0

How this code works & the ans?

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

25th Apr 2020, 11:11 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
5 Antworten
+ 2
You can't dereference 'a' argument because it is not a potiner. maybe it should be: int f(int *a, int n) and not int f(int *n, int a)? If so then the function uses recursion to iterate over all array elements. If current element is even (*a % 2 == 0) then result is the sum of the current element and the result of f() applied to remaining elements. If current element is odd then result is the difference between the current element and the result of f() applied to remaining elements. or step by step: f(a, 3) = f({12, 7, 5}, 3) *a is 12 it is even (*a % 2 is zero), so it returns sum: return *a + f(a+1, n-1) a+1 is move pointer to the next element (2nd) of the array, n-1 = 2 number of elements in the array: return 12 + f({7, 5}, 2) f({7, 5}, 2): *a = 7 it is odd, so difference is calculated return *a - f(a+1, n-1) a+1 is moved pointer to the next element (3rd), n = 2 - 1 = 1 return 7 - f({5}, 1) f({5}, 1): *a = 5 it is odd, so difference is calculated: return *a - f(a+1, n-1) a+1 is moved pointer to the next element (out of bounds), n = 1 - 1 = 0 return 5 - f(ptr, 0) as n<=0 the function returns 0 (it is base case) so, as base case has been met execution in the caller continues: f(ptr, 0) = 0 f({5}, 1) will return 5 - f(ptr, 0) = 5 - 0 = 5 f({7, 5}, 2) will return 7 - f({5}, 1) = 7 - 5 = 2 f({12, 7, 5}) will return 12 + f({7, 5}, 2) = 12 + 2 = 14 14 is the result of the function
25th Apr 2020, 12:14 PM
andriy kan
andriy kan - avatar
+ 1
This code has many errors ,I don't have knowledge in c or c++ ,lol you don't even know it's a c or c++? Anyway try to resolve those errors first and search why those * are used ,do some self learning that's the best way to understand them,then ask if you are facing any problem about specific things that you can't understand
25th Apr 2020, 11:51 AM
Abhay
Abhay - avatar
+ 1
andriy kan is correct .Very gud explaination.
27th Apr 2020, 7:58 AM
Nikhil Maroju
Nikhil Maroju - avatar
0
Thank you andriy kan❤ I edited it..
25th Apr 2020, 12:47 PM
Ashfaq Reshad
Ashfaq Reshad - avatar
- 2
I found it from sololearn challenge. I tried to understand this code & i failed, that's why i posted it. If you don’t know the answer, don’t need to say unnecessary things. Thank you. & i know It's a c language, c or c++, they are about to same, anyone who know the one, know the other one, so i add c & c++ too
25th Apr 2020, 11:58 AM
Ashfaq Reshad
Ashfaq Reshad - avatar