Search code examples
crecursionreturn-valuefactorial

Recursive factorial return statement


Why do we use return 1 to terminate the recursive function? Can any other value be used as a default value like 1.

And if we return 1 as return value of the function, then why 1 is not returned to main function.

 #include<stdio.h>
 int fact(int n)
 {
   if(n>=1)
      return (n*fact(n-1));
   else
      return 1;
 }
 int main()
 {
   int a,ans;
   scanf("%d",&a);
   ans=fact(a);
   printf("factorial of %d is %d ",a,ans);
   return 0;
  }
  /*
   explanation
          fact(4);
          if(4>=1) 4*fact(3)
          if(3>=1) 4*3*fact(2)
          if(2>=1) 4*3*2*fact(1)
          if(1>=1) 4*3*2*1*fact(0)
          if(0>=1) return 1;

  */

Solution

  • int fact(int n)
    {
        if (n >= 1)
            return n * fact(n-1);
        else
            return 1;
    }
    

    Each time the fact() function is called, it runs either the return n * fact(n-1); statement OR the return 1; statement but not both.

    You call fact(4) in main(). This is how it runs:

    main:
      compute fact(4)
      fact(4):
      |  4 >= 1?  Yes!
      |  compute 4 * fact(3)
      |    fact(3):
      |    |  3 >= 1?  Yes!
      |    |  compute 3 * fact(2)
      |    |    fact(2):
      |    |    |  2 >= 1? Yes!
      |    |    |  compute 2 * fact(1)
      |    |    |    fact(1):
      |    |    |    |  1 >= 1? Yes!
      |    |    |    |  compute 1 * fact(0)
      |    |    |    |    fact(0):
      |    |    |    |    |  0 >= 1? NO!
      |    |    |    |    |  return 1;
      |    |    |    |    +--> 1
      |    |    |    |  fact(0) is 1, return 1 * 1 (--> 1)
      |    |    |    +--> 1
      |    |    |  fact(1) is 1, return 2 * 1 (--> 2)
      |    |    +--> 2
      |    |  fact(2) is 2, return 3 * 2 (--> 6)
      |    +--> 6
      |  fact(5) is 6, return 4 * 6 (--> 24)
      +--> 24
      fact(4) is 24, assign it to `ans`, print it etc
    // end of main
    

    When a function uses the return statement (or after it executes its last statement if a return is not reached, the control is passed back to the expression that has called it.