2,108 views
0 0 votes
#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

2 Answers

1 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 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

 

 

Position:
Show:

Related questions

9 9 votes
3 3 answers
442
442 views
GO Classes asked Jun 17
442 views
What is the output of the following code?#include <stdio.h void update(int n, int *p) { if (n <= 0) return; *p = *p + n; update(n - 2, p); *p = *p + n; } int main() { int...
6 6 votes
2 2 answers
372
372 views
GO Classes asked Jun 17
372 views
What is the output of the following code?#include <stdio.h int fun(int n) { int x = n; if (n <= 0) return 0; x = x + 2; return x + fun(n - 2); } int main() { printf("%d",...
5 5 votes
4 4 answers
383
383 views
GO Classes asked Jun 16
383 views
What is the output of the following code?#include <stdio.h void g(int n); void f(int n) { if (n <= 0) return; printf("F%d ", n); g(n - 1); printf("f%d ", n); } void g(int...
6 6 votes
3 3 answers
376
376 views
GO Classes asked Jun 16
376 views
What is the output of the following code?#include <stdio.h void fun(int n) { static int x = 0; if (n == 0) return; x++; printf("%d:%d ", n, x); fun(n - 1); printf("%d:%d ...