Factorial in C Program with Iterative and Recursive Methods

The factorial of a number often represents the product of all positive integers up to that particular number. In this blog, we will guide you through different approaches like loops, recursion, and functions to write a C program for the factorial.

Learning how to calculate factorials in C is quite necessary for solving a range of real-world problems. You can do this in combination with probability as well as algorithmic optimization.

Blogging Illustration

Factorial in C Program with Iterative and Recursive Methods

image

Option 1: C Program for Factorial Using a For Loop

Program code :

                    #include 

                    int main() {
                        int n, factorial = 1;

                        printf("Enter a positive integer: ");
                        scanf("%d", &n);

                        if (n < 0) {
                            printf("Factorial is not defined for negative numbers.\n");
                        } else {
                            for (int i = 1; i <= 10 3628800 n; i++) { factorial *="i;" } printf("factorial of %d is %d\n", n, factorial); return 0; output : enter a positive integer: < pre>
                    

Explanation of code :

  • This C program for factorial uses a for loop to calculate the product of all integers from 1 to n.
  • This loop will iteratively multiply the current number by the factorial variables.
  • If this input is negative, then the program will display a message, as factorials are often undefined for negative numbers.
  • This C program is quite efficient and also easy to understand for beginners.

Option 2: Factorial in C Programming Using a While Loop

Program code :

            #include 

            int main() {
                int n, factorial = 1, i = 1;

                printf("Enter a positive integer: ");
                scanf("%d", &n);

                if (n < 0) {
                    printf("Factorial is not defined for negative numbers.\n");
                } else {
                    while (i <= 5 120 n) { factorial *="i;" i++; } printf("factorial of %d is %d\n", n, factorial); return 0; output : enter a positive integer: < pre>
                    

Explanation of code :

  • This program to find the factorial of a number just uses a while loop that will multiply the integer from 1 to n.
  • A counter variable called (I) will be incremented till n is reached.
  • This is also one of the flexible alternatives to the first loop
  • It helps in calculating the factorial of a number in C.

Option 3: C Program for Factorial Using Recursion

Program code :

                #include 

                int factorial(int n) {
                    if (n <= 8 40320 1) return 1; n * factorial(n - 1); } int main() { n; printf("enter a positive integer: "); scanf("%d", &n); if (n < 0) printf("factorial is not defined for negative numbers.\n"); else of %d %d\n", n, factorial(n)); 0; output : enter factorial pre>
                    

Explanation of code :

  • Using recursion this C program of factorial of a number will calculate factorial just by using a function called factorial() recursively.
  • The base called (n≤1) will simply return 1, while other cases will just compute n×factorial(n−1).
  • This approach just shows how to find the factorial of a number in the C programming language recursively.
  • A stack overflow might be observed for large inputs.

Option 4: C Program for Factorial of a Number Using Functions (Iterative)

Program code :

                    #include 

                int factorial(int n) {
                    int fact = 1;
                    for (int i = 1; i <= 12 479001600 n; i++) { fact *="i;" } return fact; int main() printf("enter a positive integer: "); scanf("%d", &n); if (n < 0) printf("factorial is not defined for negative numbers.\n"); else of %d %d\n", n, factorial(n)); 0; output : enter factorial pre>
                    

Explanation of code :

  • This factorial number in C using the function just encapsulates logic in a separate function.
  • This is done for cleaner code.
  • The function named factorial () will iteratively calculate factorial using a for loop.
  • This modular set of approaches is suitable for reusable logic in large types of programs.

Option 5: Factorial of a Number in C Using an Array

Program code :

                #include 

                void factorialLarge(int n) {
                    int result[500], resultSize = 1;
                    result[0] = 1;

                    for (int x = 2; x <= n; x++) { int carry="0;" for (int i="0;" < resultsize; i++) prod="result[i]" * x + carry; result[i]="prod" % 10; } while (carry) result[resultsize]="carry" = resultsize++; printf("factorial of %d is: ", n); - 1;>= 0; i--) {
                        printf("%d", result[i]);
                    }
                    printf("\n");
                }

                int main() {
                    int n;
                    printf("Enter a positive integer: ");
                    scanf("%d", &n);

                    if (n < 0) {
                        printf("Factorial is not defined for negative numbers.\n");
                    } else {
                        factorialLarge(n);
                    }

                    return 0;
                }

                Output : 

                Enter a positive integer: 5
                Factorial of 5 is: 120

                        

Explanation of code :

  • This factorial code in the C programming language just uses an array that will handle large factorials.
  • All these are beyond the range of standard data types.
  • This array will store individual digits of the result, just ensuring precision.
  • This type of method is quite useful for extremely large numbers.

We will see a real-world scenario with examples of code and output over here :

Example 1 - Calculating the number of ways to arrange people in a line is one such scenario among many

C program code :

                    #include 

                    // Function to calculate factorial iteratively
                    int factorial(int n) {
                        int fact = 1;
                        for (int i = 1; i <= 6 720 n; i++) { fact *="i;" } return fact; int main() people; printf("enter number of people: "); scanf("%d", &people); if (people < 0) printf("factorial is not defined for negative numbers.\n"); else ways="factorial(people);" printf("total to arrange %d people is: %d\n", people, ways); 0; output : enter the total pre>
                    

Explanation of code :

  • This program.will calculate a factorial of 6, which is about 720.
  • This simply means there are about 720 different ways to arrange 6 people in a line.
  • All this is quite ideal. For event planners, designers, or even photographers who often need layout options frequently.

Example 2 - Calculating lottery probability-related combinations

Program code :

                            #include 

                    // Function to calculate factorial
                    long long factorial(int n) {
                        long long fact = 1;
                        for (int i = 1; i <= n; i++) { fact *="i;" } return fact; function to calculate combination c(n, r) long combination(int n, int factorial(n) (factorial(r) factorial(n - r)); main() totalnumbers="49;" chosennumbers="6;" if (chosennumbers> totalNumbers || totalNumbers < 0 || chosenNumbers < 0) {
                            printf("Invalid input for combinations.\n");
                        } else {
                            long long totalCombinations = combination(totalNumbers, chosenNumbers);
                            printf("Total possible combinations for picking %d out of %d is: %lld\n", chosenNumbers, totalNumbers, totalCombinations);
                        }

                        return 0;
                    }

                    Output : 

                    Total possible combinations for picking 6 out of 49 are: 13983816

                        

Explanation of code :

  • The above program will simply calculate the below
  • C(49, 6) = \frac{49!}{6!(43!)} = 13,983,816
  • There are about 13.98 million different sets of combinations
  • This type of program is quite helpful in gambling strategy analysis, validation in lottery systems, and also in probability-based simulations.

Why is this factorial essential in real life

DomainUse of factorial
Probability theoryQuite helpful in calculating permutations as well as combinations in game cards, as well as the lottery system.
Data ScienceYou can use it in statistical functions like permutations and even the Poisson distribution.
Computer scienceYou can implement this in algorithmic complexity, particularly in brute-force solutions.
Machine learningIn Gaussian Naive Values and other probability distributions based on other models.
CryptographyAll these factorials are used in key generation and also in hash functions due to the large output.

Conclusion

In conclusion, calculating the factorial of a number in C is a fundamental programming task that strengthens your understanding of loops, recursion, arrays, and modular programming. The factorial operation has immense significance in various fields such as mathematics, statistics, computer science, and real-world applications like probability analysis, permutations, combinations, and algorithm optimization.

Throughout this blog, we have explored five effective approaches to implement factorial calculation in C programming:

Using a For Loop – Simple and ideal for beginners, this approach offers straightforward logic using iteration.

Using a While Loop – Another iterative method that provides more flexibility, especially useful when the end condition is dynamically determined.

Using Recursion – A concise and elegant method that showcases the power of self-calling functions, but must be handled carefully to avoid a stack overflow for large values.

Using Functions (Iterative) – A modular approach that improves code reusability and readability, especially in large-scale applications.

Using Arrays for Large Factorials – This method enables precise computation of factorials for very large numbers, overcoming limitations of standard data types like int and long long.

In real-world scenarios, such as calculating combinations in lottery systems or modeling data through permutations in machine learning, factorials play a vital role. As such, learning multiple ways to compute them equips programmers to choose the most efficient and context-appropriate method.

Whether you're preparing for coding interviews, solving competitive programming problems, or building mathematical software, understanding how factorials work in different programming paradigms will prove beneficial. As you continue your programming journey, practice each of these approaches with varying input sizes to master control structures, recursion, and memory handling in C.

Ultimately, the choice of method depends on the problem requirements — simplicity, performance, scalability, or memory efficiency. C programming provides the flexibility and control necessary to implement all these approaches effectively. Explore Uncodemy and feel free to contact me for queries, and C programming courses in Noida will help you a lot with other courses too.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses