edited by
926 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

3 votes
3 votes
3 answers
1
Laxman Ghanchi asked May 19, 2023
1,113 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
2
Laxman Ghanchi asked May 19, 2023
657 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
3
parasghai28 asked Jul 8, 2018
1,923 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 ...
1 votes
1 votes
1 answer
4
parasghai28 asked Jul 8, 2018
1,001 views
void ab() { auto int a; static int s= 5; a = ++s; printf("%d%d",a,s); if(a<= 7) ab(); printf("%d%d",a,s); } void main() { ab(); }According to me answer should be- 6677888...