+ 1

Hi there! Need help understanding simple C program output.

Hi! I was wondering why following function has the given output: int main() { tree(3); return 0; } void tree(int n) { if(n > 1) // edited typo { tree(n-1); printf("%d\n", n); tree(n-1); printf("%d\n", n); } } Output: 2 2 3 2 2 3 I don't understand how 3 comes up there and why it loops in an if statement! Any explanation would be appreciated!

25th Jan 2023, 6:39 PM
Sarah Nour El Din
Sarah Nour El Din - avatar
5 Antworten
+ 3
It's a recursive function, tricky to understand. See first you call tree(3): 3>1 is true so in if block, it call a new function call tree(3-1) => tree(2). This is new call so still previous call tree(3) is pushed to stack with n=3. Note this. will be returned to this after inner recursions completed. tree(2) tree(2-1) => calls tree(1) , here 1>1 so function does nothing. Goes back to previous call tree(2-1), the next statement is print("%d\n", n); so prints 2. Next statement is tree(2-1) so does same as tree(1) call. Come backs and prints prints("%d\n", n) ; #2 this ends tree(3-1) so next call is print 3 you have same repeating code,so tree(3-1) just the same repeatation for second inner recursive call tree(3) tree(3-1): tree(2) tree(2-1) => tree(1) prints("%d",n); #2 tree(2-1) => tree(1) prints("%d",n); #2 goes back tree(3-1) call so prints 3 tree(3-1): tree(2) tree(2-1) => tree(1) x prints("%d",n); #2 tree(2-1) => tree(1) x prints("%d",n); #2 goes back tree(3-1) call so prints 3 hope it helps...
25th Jan 2023, 7:35 PM
Jayakrishna ­čç«­čç│
+ 2
Sarah Nour El Din A function is recursive, when it calls itself recursively. There must be stop condition at some point. Otherwise infinite recursive. See ex: void fun(n) { printf("%d ", n); if( n > 0) fun(n-1); } Calling this function fun(5), it prints 5 4 3 2 1 0 The function fun() calling itself within the function body so it is a recursive function call. if you don't place if( n > 0) then it calls infinitely with negative values going on...
25th Jan 2023, 8:08 PM
Jayakrishna ­čç«­čç│
+ 1
Are you sure about output? It won't output anything.. n > n always results to false..
25th Jan 2023, 6:57 PM
Jayakrishna ­čç«­čç│
+ 1
Jayakrishna ­čç«­čç│ omg you're so right that's a mistake on my part its supposed to be (n>1)
25th Jan 2023, 6:59 PM
Sarah Nour El Din
Sarah Nour El Din - avatar
+ 1
Jayakrishna ­čç«­čç│ Thanks so much, I'm getting closer to understanding it. Is an if statement always a recursive function? Or what marks a recursive function? I'll try to wrap my head around it to fully grasp it :)
25th Jan 2023, 7:56 PM
Sarah Nour El Din
Sarah Nour El Din - avatar