Menu

Add Topic

programming

waiting answer July 28, 2021

Factorial program in C

Answers
July 09, 2021

Factorial in C programming logic can be done in many ways

  • Using for loop
  • Using function
  • Using recursion

To understand this program, You should have basic knowledge of

  • C Data types
  • C Operators
  • C loops (For loop, while loop and do-while loop)

NOTE:

  • factorial of 0 = 1
  • We cannot find factorial of a negative number and it does not exist
  • Example: factorial of 5 = 5*4*3*2*1 = 120

Factorial in C using for loop

    #include<stdio.h>  
    int main()    
    {    
     int i,num,fact=1;    
     printf("Enter a positive number: ");    
      scanf("%d",&num);    
        for(i=1;i<=num;i++){    
          fact=fact*i;    
      }    
      printf("Factorial of the number %d is: %d",num,fact);    
    return 0;  
    }   

Output:

         Enter a number: 5
         Factorial of the number 5 is: 120

0 0
July 09, 2021

The factorial of a non-negative integer is the product of all positive integers less than or equal to n, where n is a non-negative integer.

             n!=n*(n-1)*(n-2)*....*2*1

Example

            5!=5*4*3*2*1=120

Factorial program in C using Recursion

    #include <stdio.h>

    int factorial(int num)
    {
        if (num == 0){
            return 1;
        }else{
            return num * factorial(num - 1);
        }
    }
      
    int main()
    {
        int num;
        printf("Enter a positive number: ");
        scanf("%d",&num); 
        printf("Factorial of %d is %d",
               num, factorial(num));
        return 0;
    }

Output:

         Enter a positive number: 5
         Factorial of 5 is 120

0 0
July 12, 2021

There are different ways in the C program to find the factorial of a number. Let's see how to write a c program to find the factorial of a number using C.

    #include<stdio.h>  
    int main()    
    {    
      int number;
      int i;
      int fact=1;    
      printf("Enter a number: ");    
      scanf("%d",&number);    
      for(i=1;i<=number;i++){    
          fact=fact*i;    
      }    
      printf("Factorial of the number %d is: %d",number,fact);    
    }

Output:

         Enter a number: 2
         Factorial of the number 2 is: 2    

0 0
January 04, 2021

Factorial Program using recursion in C

    #include<stdio.h>  
  
    long factorial(int num)  
    {  
      if (num == 0)  
        return 1;  
      else  
        return(num * factorial(num-1));  
    }  
       
    void main()  
    {  
      long fact;    
      int number; 
      printf("Enter a number: ");  
      scanf("%d", &number);   
      fact = factorial(number);  
      printf("Factorial of the number %d is %ld\n", number, fact);  
      return 0;  
    }

OUTPUT

        Enter a number: 5
        Factorial of the number 5 is 120

0 0

Please Login to Post the answer

Leave an Answer