C Example for Beginners: C Program to Find Factorial of a Number

Hits: 5

(C programming Example for Beginners)

C Program to Find Factorial of a Number

In this example, you will learn to calculate the factorial of a number entered by the user.


The factorial of a positive number n is given by:

factorial of n (n!)= 1 * 2 * 3 * 4....n

The factorial of a negative number doesn’t exist. And, the factorial of 0 is 1.


Factorial of a Number


#include <stdio.h>
int main(){
    int n, i;
    unsigned long long fact = 1;
    printf("Enter an integer: ");
    scanf("%d", &n);

    // shows error if the user enters a negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");
    else {
        for (i = 1; i <= n; ++i) {
            fact *= i;
        }
        printf("Factorial of %d = %llu", n, fact);
    }

    return 0;
}

Output

Enter an integer: 10
Factorial of 10 = 3628800

This program takes a positive integer from the user and computes the factorial using for loop.

Since the factorial of a number may be very large, the type of factorial variable is declared as unsigned long long.

If the user enters a negative number, the program displays a custom error message.

 

 

C Example for Beginners: C Program to Find Factorial of a Number

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.