edited by
1,633 views
4 votes
4 votes

Consider the following function:

void madeeasy (int n)
 {
   if (n < 0) return;

   else
 {
   printf(n);
   madeeasy (- -n);
   madeeasy (n - -);
   printf(n);
 }
 
}


The sum of all values printed by madeeasy (5)_______

(I am getting -12 but given answer is 52)

edited by

3 Answers

1 votes
1 votes

Case 1 : If termination condition is on n<0 ;

if (n < 0)

then answer will be -12

 

Case 2 : if termination condition is n<=0

if (n <= 0)

then answer will be  52

0 votes
0 votes

Whenever the function decreases the recursive call value, it's better do follow a bottom up approach.

I'll rename madeeasy() to m() for simplicity.


m(0) runs like this:

print 0

m(-1); starting m(-1) is pointless, as it just makes us return.

m(-1)

print -2

Hence, Sum = -2

m(1) runs like this:

print 1

m(0); We know m(0) gives us sum -2.

m(0); We know m(0) gives us sum -2.

print -1

Hence, Sum = -4

Similarly, m(2) gives us sum: -6

m(3) gives us sum: -8

m(4) gives us sum: -10

m(5) will give us -12.