C program to find factorial of a number-Factorial c proramming

 C program to find factorial of a number

Here, we will learn a short program an example of loop finding the factorial of a number. First we will initialize a variable named 'fact' to 1. then we will un the for loop from one to n. And inside the for loop we will multiply fact with index value 'i' each time through the loop. 


Algorithm:-

  1. Start
  2. Initialize fact to 1
  3. Read n from user
  4. Run loop from i=1 to n and do
  5. fact=fact*i
  6. Print the output
  7. End.
C programming
C Program to find factorial of number


What is factorial of a number

the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n:

n! = n x (n-1) x (n-2) x . . . x 3 x 2 x 1

For example:-

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



Program using for loop

Here we are first declaring n to take the number from the user and initializing the variable fact to one and this variable will store the final result that will be printed on the screen. In this program we are using the for loop to find the factorial of a number. We are running the for loop from 1 to n and we are calculating the factorial by fact=fact*i (for e.g 5 factorial = 1*2*3*4*5=120) and after computing the value of factorial of a number we are printing the result which is stored in the fact variable.


#include <stdio.h>

int main()
{
    int n, fact=1;
    printf("Enter the value of n: ");
    scanf("%d", &n);
    
    for(int i=1;i<=n;i++){
        fact=fact*i;
    }
    
    printf("The factorial of %d is: %d", n, fact);

    return 0;
}


Output

Enter the value of n: 3                                                                                               
The factorial of 3 is: 6 

Enter the value of n: 5                                                                                               
The factorial of 5 is: 120  

Program using While loop

This program is doing the same as implemented in the above program using for loop. Here instead of using for loop we are using while loop to find the factorial of a number. Refer the program given below

#include <stdio.h>

int main()
{
    int n, fact=1;
    printf("Enter the value of n: ");
    scanf("%d", &n);
    
    int i = 1;
    
    while(i<=n){
        fact=fact*i;
        i++;
    }
    
    printf("The factorial of %d is: %d", n, fact);

    return 0;
}

Output

Enter the value of n: 5                                                                                               
The factorial of 5 is: 120 

Enter the value of n: 4                                                                                               
The factorial of 4 is: 24 

Post a Comment

0 Comments