in Programming in C edited by
938 views
1 vote
1 vote
#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.

in Programming in C edited by
938 views

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

4 Comments

what condition should we employ to the while loop so that the function correctly return the output ?
1
1
the while loop dont encounter at fun(0) and return zero to previous function fun(1) return zero to fun(2) this process continues  ,at last fun(8) receives zero
0
0

Thank you @benarji_2001

0
0

The correct while loop would be 

while(n>=1){
    // your code
}

or you can further modify it to be

while(n!=1){
    // your code here
}

 

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