Saturday, 23 May 2020

C program to find factorial using recursion


C program to find  factorial using recursion:
2! = 1*2 =2
                3! = 1*2*3 =6
                4! = 1*2*3*4 = 24
                5! = 1*2*3*4*5 = 120
                6! = 1*2*3*4*5*6 = 720
                7! = 1*2*3*4*5*6*7 = 5040
                8! = 1*2*3*4*5*6*7*8 = 40320

 Below is the c program to find factorial using recursion.


#include <stdio.h>
int factorial(int n){
                int i, fact=1;
                                if( n==0 || n== 1)
                                                fact=1;
                                else
                                                fact = n * factorial( n-1);
               
                return fact;
}
void main(){
   int number, i, fact =1;
   printf("provide the number to find factorial. ");
   scanf("%d",&number);
  
   // check number is greater than zero or not.
   if( number>=0){
          //  calling the factorial function to find factorial.
       fact= factorial(number);
                   printf("factorial of given number is %d", fact);
   }
   else{
                printf("factorial not defined for negative values....");
                printf("please enter positive numbers ");
                }
}

Output:
provide the number to find factorial.
5
factorial of given number is 120

Output:
provide the number to find factorial.
   1
factorial of given number is 1

Output:
provide the number to find factorial.
0
factorial of given number is 1

Output:
provide the number to find factorial.
     -5
  factorial not defined for negative values....
  please enter positive numbers


5! =    5 * factorial ( 4 )
                  4 *  factorial ( 3 )
                                2 *  factorial ( 2 )
                                                2 *  factorial ( 1 )
                                                                1

No comments:

Post a Comment