By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,640 Members | 2,167 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,640 IT Pros & Developers. It's quick & easy.

plz help me....I can't understand the answer to the following program

P: 1
#include<stdio.h>

void crazy(int a,int b, int m, int n)
{
if(n==0)
return;
crazy(a+m,b,m+b,n-1);
printf("%d %d %d %d ",a,b,m,n);
printf("\n");
crazy(a,b+m,m+a,n-1);
}

int main()
{
crazy(2,5,1,3);
return (0);
}


what is the output?? i am confused about this
Oct 21 '15 #1
Share this Question
Share on Google+
5 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
What don't you understand?

This is an example of recursion.
Oct 21 '15 #2

Expert 100+
P: 2,400
What output did you get?
Oct 22 '15 #3

P: 16
recursion 1:
a=2 b=5 m=1 n=3

recursion1.1:
a=2+1 b=5 m=1+5 n=2

recursion 1.1.1:
a=3+6 b=5 m=6+5 n=1

recursion 1.1.1.1:
a=9+11 b=5 m=11+5 n=0

return
print-> 20 5 16 0

The second recursion call makes it very complex. you have to handle two recursions that are kinda nested.
Working out the second part....I guess ill leave it to you. :p
Oct 23 '15 #4

weaknessforcats
Expert Mod 5K+
P: 9,197
I am concerned that you have two calls to crazy() inside
crazy().

Usually there is only one recursive call:

Expand|Select|Wrap|Line Numbers
  1. void crazy(int a,int b, int m, int n)
  2. {
  3.    if(n==0)
  4.      return;
  5.    printf("%d %d %d %d ",a,b,m,n);
  6.    printf("\n"); 
  7.    crazy(a,b+m,m+a,n-1);
  8. }
  9.  
In this example you print if n is not zero then call crazy() with new argument values. Those value get printed in the next call, which changes the values and calls crazy()again.

Finally, n is zero and that remote crazy() returns causing the next remote to return, until the first call to crazy() returns.

The number of lines you print would be the number of calls in the recursion.
Oct 23 '15 #5

Expert 100+
P: 2,400
@jaseel97 I agree except for the last line. I think it will be
print-> 9 5 11 1
because crazy(a,b,m,0) doesn't print anything.

My pencil-and-paper analysis suggests a pattern -- for crazy(a,b,m,n), the number of lines printed will be 2^(0) + 2^(1) + ... + 2^(n-1) = 2^(n) - 1. The pattern looks like a family tree.

@AndrewCool Have you run this program yet? If so, what was the output?
Oct 23 '15 #6

Post your reply

Sign in to post your reply or Sign up for a free account.