+ 7

Find the output.n=5

int recur(int n) { return !n?0: recur(n-1)+1+recur(n-1); }

18th Feb 2018, 6:06 AM
nandhini
nandhini - avatar
4 Answers
+ 7
n = 5 !n = false Function returns recur(4) + 1 + recur(4) Top level statement: recur(4) + 1 + recur(4) = 2 * recur(4) + 1 n = 4, !n = false Function returns recur(3) + 1 + recur(3) Top level statement: 2 * (recur(3) + 1 + recur(3)) + 1 = 4* recur(3) + 3 n = 3 !n = false Function returns recur(2) + 1 + recur(2) Top level statement: 4* (recur(2)+1+recur(2)) + 3 = 8* (recur(2)) + 7 n = 2 !n = false Function returns recur(1) + 1 + recur(1) Top level statement: 8 * (recur(1)+1+recur(1)) + 7 = 16 * (recur(1)) + 15 n = 1 !n = false Function returns recur(0) + 1 + recur(0) Top level statement: 16 * (recur(0)+1+recur(0)) + 15 = 32 * (recur(0)) + 31 n = 0 !n = true Function returns 0 Top level statement: 32 * (0) + 31 = 31 Ans : 31
18th Feb 2018, 8:10 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
would you explain once sirr
18th Feb 2018, 7:07 AM
Lavanya Kumar.B
Lavanya Kumar.B - avatar
+ 2
So for 0 the function returns 0. otherwise it return 2*f(n-1) +1. So you get: 0 -> 0 1 -> 1 2 -> 3 3 -> 7 4 -> 15 5 -> 31 Note​ the function will try work out the result in the reverse order and make recursive calls to get the answer. It will also make two calls​ for every level instead of doubling the number.
18th Feb 2018, 8:05 AM
Jared Bird
Jared Bird - avatar
- 2
31. It's not too hard to work out by hand, or you can run it and see.
18th Feb 2018, 6:42 AM
Jared Bird
Jared Bird - avatar