How to Write a Factorial Program in C with Code Examples

Published: 13 November 2025
Reading Time: 6 minutes
Source: NxtWave CCBP Blog

Table of Contents

Key Takeaways From the Blog

Introduction

In mathematics, factorial is the product of all the positive integers that are less than or equal to the number whose factorial is required. For example, the factorial of 5 is written as:

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

Factorials have important applications in:

This article provides a comprehensive look at writing factorial programs in C, covering multiple implementation approaches with detailed code examples.

What is a Factorial Program in C?

A factorial program in C is code that performs the multiplication required to find the factorial of a number. In C, this can be accomplished using several techniques:

Implementation Techniques

Key Programming Elements

Data Types: Variables must be declared with appropriate data types to store numbers:

Operators Used:

Control Structures:

Algorithm for Factorial Program in C

Here is the general algorithm for a C program to find the factorial of a number:

Step-by-Step Algorithm

  1. Begin the program
  2. Define variables to hold the number entered by the user and the resulting factorial
  3. Display a message asking the user to provide a number
  4. Accept the input from the user
  5. Initialize the variable by storing the factorial result as 1
  6. Implement a loop (like a for or while loop) to run from 1 to the user's number
  7. Within the loop, update the factorial result by multiplying it with the current loop counter
  8. Once the loop finishes, the factorial result will contain the desired value
  9. Output the calculated factorial
  10. Conclude the program

Key Point: The factorial algorithm is direct: initialize, iterate, multiply sequentially, and print the result.

Input and Output Handling in C

Proper input and output handling is crucial for any C program. In factorial programs, this involves prompting the user, reading input, and displaying results.

Implementation Approach

The program typically starts in the main() function with variable declarations:

Input/Output Functions

printf() Function:

scanf() Function:

Error Handling

Important to include validation for negative numbers:

Example Code Snippet

#include <stdio.h>

int main() {
    int n;
    unsigned long long factorial = 1;

    printf("Enter an integer: "); // prompt message
    scanf("%d", &n); // reading input

    // error handling for negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");
    else {
        for (int i = 1; i <= n; ++i) {
            // for loop
            factorial *= i;
        }
        printf("Factorial of %d = %llu", n, factorial); // printing result
    }

    return 0;
}

Key Takeaways

Factorial Program Using for Loop

The for loop is a frequently used method in C for calculating a number's factorial. The program runs a block of code repeatedly and multiplies the result variable by the loop counter at each step.

How It Works

The loop continues from 1 to the input number until it produces the factorial value.

Complete Code Example

// C program to Find the Factorial Using for Loop
#include <stdio.h>

unsigned int factorial(unsigned int N) {
    int fact = 1, i;

    // Loop from 1 to N to get the factorial
    for (i = 1; i <= N; i++) {
        fact *= i;
    }

    return fact;
}

int main() {
    int N = 5;
    int fact = factorial(N);
    printf("Factorial of %d is %d", N, fact);
    return 0;
}

Output

Factorial of 5 is 120

Advantages of for Loop Method

Factorial Program Using while Loop

A factorial program in C using a while loop repeatedly multiplies numbers from 1 up to the given input. The loop runs as long as the counter is less than or equal to the input number.

Implementation Details

Each iteration updates the factorial result, making it an effective way to calculate factorials iteratively.

Complete Code Example

#include<stdio.h>

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

    printf("Enter a number: ");
    scanf("%d", &number);

    while(number > 1) {
        factorial = factorial * number;
        number--;
    }

    printf("Factorial is: %d", factorial);
    return 0;
}

How the while Loop Works

  1. Initialize factorial to 1
  2. Read input number
  3. While number is greater than 1:
    • Multiply factorial by current number
    • Decrement number
  4. Print the result

Factorial Program in C Using Recursion

In the recursive approach, a function calls itself to solve smaller subproblems of the original problem. Each recursive call breaks the problem into simpler parts and works towards a base case.

Recursive Logic

The base case defines the stopping condition. In factorial calculation:

How Recursion Works

The factorial function keeps calling itself with number - 1 as long as the number is 1 or greater. Each recursive call multiplies the current number by factorial(number - 1). When the number becomes less than 1, the function stops and returns 1.

Complete Code Example

#include<stdio.h>

long int factorial(int number) {
   if(number >= 1)
       return number*factorial(number-1);
   else
       return 1;
}

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    printf("Factorial of %d is: %ld", number, factorial(number));
    return 0;
}

Recursion Characteristics

Factorial Program in C Using Arrays

A factorial program in C can use arrays to handle very large numbers. Arrays store individual digits of the factorial result, allowing calculations that go beyond the usual integer limits.

Why Use Arrays?

Standard data types have limits:

Implementation Method

Multiplication is done digit by digit, and results are saved in the array. This method is efficient for calculating factorials of extremely large numbers.

Complete Code Example

#include <stdio.h>
#include <string.h>

// Function to multiply a string (representing a number)
// by an integer
void multiplyString(char num[], int factor) {
    int len = strlen(num);
    int carry = 0;

    for (int i = len - 1; i >= 0; i--) {
        int digit = num[i] - '0';
        int product = digit * factor + carry;
        num[i] = (product % 10) + '0';
        carry = product / 10;
    }

    // Handling the carry by adding digits to the front
    // of the number
    while (carry) {
        for (int i = strlen(num); i >= 0; i--) {
            num[i + 1] = num[i];
        }
        num[0] = (carry % 10) + '0';
        carry /= 10;
    }
}

// Function to find factorial using a string
void factorialString(int N) {

    // Use a large enough buffer
    char fact[1000];

    // Initialize result as "1"
    strcpy(fact, "1");

    for (int i = 2; i <= N; i++) {

        // Multiply the string in each iteration
        multiplyString(fact, i);
    }

    printf("Factorial of %d is %s", N, fact);
}

int main() {
    int N = 5;
    factorialString(N);
    return 0;
}

Key Takeaways

Factorial Program in C Using Ternary Operator

A factorial program in C can be designed with minimal statements by using the ternary operator. The ternary operator behaves as a compact conditional, checking whether the number is less than or equal to one (base case returns 1), otherwise it multiplies the number by the factorial of one less number recursively.

Ternary Operator Syntax

The ternary operator format: condition ? value_if_true : value_if_false

Complete Code Example

#include<stdio.h>

long int factorial(int number) {
   return (number >= 1) ? number*factorial(number-1) : 1;
}

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    printf("Factorial of %d is: %ld", number, factorial(number));
    return 0;
}

Advantages

Key Point: The ternary operator provides concise, elegant syntax for recursive factorial implementation.

Factorial Program to Find Factorial Series in C

The factorial series program calculates the factorials of numbers from 0 up to a given number. The program uses a loop to calculate the factorials of each number in sequence and displays them.

Implementation Approach

Another loop or recursion is used within the main loop to calculate individual factorials, which are then stored and displayed in sequence.

Complete Code Example

#include<stdio.h>

long int factorial(int number) {
   long int fact = 1;

   for(int i = 1; i <= number; i++) {
      fact = fact * i;
   }

   return fact;
}

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    for(int i = 0; i <= number; i++) {
        printf("Factorial of %d is: %ld\n", i, factorial(i));
    }

    return 0;
}

Key Takeaways

Example Output

If user enters 5:

Factorial of 0 is: 1
Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120

Conclusion

Writing a factorial program in C is a valuable initial programming exercise that provides good knowledge and strengthens problem-solving skills. It helps learners appreciate various control structures such as:

You can make errors here and learn from them to advance to higher-level code. Moreover, understanding factorial logic builds a foundation for tackling more advanced algorithms and mathematical problems in programming.

Why It Matters

Understanding factorial programs is a great way for learners to build their confidence in:

It demonstrates how iterative and recursive logic can be used to solve complex problems efficiently. Proficiency in factorials is essentially the starting point for dealing with algorithms that include:

Practical Advice for Learners

  1. Practice both approaches: Use both loops and recursion to compare performance
  2. Experiment with large numbers: Try array-based solutions for very large factorials
  3. Add error handling: Include validation for invalid or negative inputs
  4. Optimize recursive versions: Study techniques to reduce memory usage in recursion
  5. Study applications: Learn how factorial logic applies to permutations and combinations

Frequently Asked Questions

What is a factorial?

A factorial of a number is the result of multiplying all positive whole numbers from 1 up to that number. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

How does recursion work in calculating factorials?

Recursion involves a function calling itself with a reduced number. It multiplies the result until it reaches the base case, which is usually 1. The recursion ends once it reaches that base case.

How to calculate large factorials in C?

For very large factorials, you can use arrays. Arrays can store individual digits or libraries designed for big-number calculations and get the results.

What is the difference between a loop and recursion for factorial calculation?

A loop repeatedly executes a block of code until the factorial is arrived at. Recursion calls the function within itself. Both methods yield the same result but use different approaches.

How do I improve the efficiency of my factorial program?

If you are looking for efficiency, using iterative methods like loops is more memory-efficient than recursion. Additionally, storing previously computed results can speed up the process for large numbers.


Related Articles


About NxtWave: NxtWave provides comprehensive programming education and career development resources for students and professionals. Contact: [email protected] | WhatsApp: +919390111761

Source: This content is from NxtWave CCBP Blog - https://www.ccbp.in/blog/articles/factorial-program-in-c