search
Log In
0 votes
211 views
#include<stdio.h>
void print(int n)
{
    if (n > 4000)
        return;
    printf("%d ", n);
    print(2*n);
    printf("%d ", n);
}

int main()
{
    print(10);
    getchar();
    return 0;
}
 

PLEASE EXPLAIN THE OUTPUT
in Programming 211 views

2 Answers

1 vote

You can do it using recursion tree or stack.

Let these be line numbers:

1. if (n > 4000) 
2.       return; 
3.    printf("%d ", n); 
4.    print(2*n); 
5.    printf("%d ", n); 

Whenever print(int n) is recursively called, the 5th line will be executed once the recursive call is over and so on.

0 votes

First of all the answer to this question is :

10 20 40 80 160 320 640 1280 2560 2560 1280 640 320 160 80 40 20 10

 

At the initial call print(10) is called, the if (n > 4000) is not true and it prints the next statement  i.e printf("%d ", n); ie 

Output : 10 

 

For convenience and understanding  i am gonna number the statements from 

  1  if (n > 4000) 
  2     return; 
  3  printf("%d ", n); 
  4  print(2*n); 
  5  printf("%d ", n); 

The printf in stat 3 is executed till n =2560 . As soon as print(2560*2) is called ie n becomes 5120. Now the statement 1 returns true and returns to the previous callee at statement 5 with n = 2560, prints that and that function exits to the previous callee with n to be 2560 and so on .. 

Let me know if u still have confusions

 

 

Related questions

0 votes
0 answers
2
68 views
Its always a confusion how Recursion works with for loop. Explain a brief.
asked Jan 7, 2019 in Programming HeadShot 68 views
0 votes
0 answers
3
29 views
NOT GGETTING THIS STATEMENT “Recursion is not useful for branching processes” WHAT DOES IT MEANS?
asked Dec 29, 2018 in Programming eyeamgj 29 views
0 votes
2 answers
4
154 views
How 22 ?
asked Nov 12, 2018 in Programming HeadShot 154 views
...