C Program To Find Factorial of a Number


Write a C program to find Factorial of a user input number, using while loop.

Related Read:
while loop in C programming
Assignment Operators in C

Factorial of a number is the product of all the numbers preceding it. For example, Factorial of 5 is 120 (1 x 2 x 3 x 4 x 5 = 120).

In general, n objects can be arranged in n(n – 1)(n – 2) … (3)(2)(1) ways. This product is represented by the symbol n!, which is called n factorial. By convention, 0! = 1.

Source Code: C Program To Find Factorial of a Number

 
#include<stdio.h>

int main()
{
    long int num, count = 1, fact = 1;

    printf("Enter a number to find factorial\n");
    scanf("%d", &num);

    while(count <= num)
    {
        fact = fact * count; // fact *= count;
        count++;
    }

    printf("Factorial of %d is %d\n", num, fact);

    return 0;
}

Output 1:
Enter a number to find factorial
4
Factorial of 4 is 24

Output 2:
Enter a number to find factorial
5
Factorial of 5 is 120

Output 3:
Enter a number to find factorial
6
Factorial of 6 is 720

Output 4:
Enter a number to find factorial
8
Factorial of 8 is 40320

Output 5:
Enter a number to find factorial
10
Factorial of 10 is 3628800

C Program To Find Factorial of a Number using While Loop


[youtube https://www.youtube.com/watch?v=43RdmXXcr6Y]

YouTube Link: https://www.youtube.com/watch?v=43RdmXXcr6Y [Watch the Video In Full Screen.]


Logic To Find Factorial of a Number

If user enters num as 4. Then here are the values of variable count and fact for each iteration of while loop.

Iteration 1
count = 1;
fact = 1;

fact = fact * count;
fact = 1 * 1;

count = 2; // value of count increments by 1 for each iteration.
fact = 1;

Iteration 2
count = 2;
fact = 1;

fact = fact * count;
fact = 1 * 2;

count = 3; // value of count increments by 1 for each iteration.
fact = 2;

Iteration 3
count = 3;
fact = 2;

fact = fact * count;
fact = 2 * 3;

count = 4; // value of count increments by 1 for each iteration.
fact = 6;

Iteration 4
count = 4;
fact = 6;

fact = fact * count;
fact = 6 * 4;

count = 5; // value of count increments by 1 for each iteration.
fact = 24;

Now the value of count is 5, which is greater than the user input number 4. So the control exits while loop. We print the value present inside variable fact as the Factorial of the number. So in this case, 24 is the Factorial of number 4.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *