edited by
964 views
1 votes
1 votes
#include <stdio.h>
int fun(int num)
{
    while(num>0)
    {
        num=num*fun(num-1);
    }
    return num;
}
int main()
{
    int x=fun(8);
    printf("%d",x);
    return 0;
}


Hello Folks, I have a doubt related to the above snippet of code.

Why does the output of the above code be 0?

Kindly help me with a detailed explanation.

edited by

2 Answers

3 votes
3 votes
Let's check at the fun(0)

it doesn't enter into for loop

and returns zero, which is multiplied by every function and returns num=num*0

which means zero at the main function
0 votes
0 votes
fun(8) = 8 * fun(7)
       = 8 * (7 * fun(6))
       = 8 * (7 * (6 * fun(5)))
       = 8 * (7 * (6 * (5 * fun(4))))
       = 8 * (7 * (6 * (5 * (4 * fun(3)))))
       = 8 * (7 * (6 * (5 * (4 * (3 * fun(2))))))
       = 8 * (7 * (6 * (5 * (4 * (3 * (2 * fun(1)))))))
       = 8 * (7 * (6 * (5 * (4 * (3 * (2 * (1 * fun(0))))))))
       = 8 * (7 * (6 * (5 * (4 * (3 * (2 * (1 * 0)))))))
       = 8 * (7 * (6 * (5 * (4 * (3 * (2 * 0))))))
       = 8 * (7 * (6 * (5 * (4 * (3 * 0)))))
       = 8 * (7 * (6 * (5 * (4 * 0))))
       = 8 * (7 * (6 * (5 * 0)))
       = 8 * (7 * (6 * 0))
       = 8 * (7 * 0)
       = 8 * 0
       = 0
You can also use tree method for solving this problem:

              fun(8)
               / \
              /   \
         8 * fun(7)
             / \
            /   \
       7 * fun(6)
           / \
          /   \
     6 * fun(5)
         / \
        /   \
   5 * fun(4)
       / \
      /   \
  4 * fun(3)
      / \
     /   \
3 * fun(2)
     / \
    /   \
2 * fun(1)
     / \
    /   \
1 * fun(0)
     |
     0
so FInal Answer will be =0

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 10
104 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
3 votes
3 votes
3 answers
2
Laxman Ghanchi asked May 19, 2023
1,160 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...
0 votes
0 votes
1 answer
3
Laxman Ghanchi asked May 19, 2023
685 views
#include<stdio.h>void print(int n){ printf("Hello "); if(n++ == 0) return ; print(n); n++;}int main(){ void print(); print(-4);}
2 votes
2 votes
2 answers
4
parasghai28 asked Jul 8, 2018
1,970 views
int f (int n){ if (n==0) return 0; if(n==1) return 1;elsereturn f(n-1)+f(n-2);}Find the upper bound and lower bound to the number of function ...