View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Factorial Program in C

Updated on 23/06/202532,827 Views

Can you write a factorial program in C using loops, recursion, and even built-in math functions like tgamma()? If you're exploring how to calculate the factorial of a number in C, there’s more than one way to do it. From simple iterative loops to recursion, and from pointer-based logic to one-liners with the ternary operator, each method reveals a new layer of how C handles memory, functions, and performance.

In this tutorial, you’ll learn how to write a C program to find the factorial of a number using multiple approaches:

  • For and while loops
  • Recursion and ternary logic
  • The tgamma() math function
  • Functions and pointers

Each section includes code, explanations, and execution flow so you can choose the best method for your use case.

Want to master core programming concepts like loops, recursion, and memory management?

Check out upGrad’s Software Engineering Courses to build your skills with real-world projects and expert mentorship.

Now, let’s understand what factorials are and how to calculate them mathematically.

What is a Factorial?

A factorial is the product of all positive integers from 1 to a given number (n). It is represented by the symbol n!

Mathematical Definition

n! = n × (n − 1) × (n − 2 )× … × 3 × 2 × 1

Special case

0! = 1

Now, let’s have an example to get a better understanding

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

So, 5! = 120

Now, it’s time to explore different methods to find the factorial of a number in C programming.

How to Write a C Program to Find the Factorial of a Number?

In this section, we will explore different methods to find the factorial of a number in C Programming.

Method- 1: Factorial Program using Iterative Solution

Iterative solutions are those that employ loops for solving problems. Let's understand how to calculate factorials using iterative solutions.

Using For Loop to find the Factorial of a Number in C Programming

The 'for' loop is one of the most common iterative solutions in C programming. It iterates over a block of code a certain number of times. Here is how we can find the factorial of a number in C using a 'for' loop.

#include<stdio.h>

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

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

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

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

In the above code, we initialize factorial to 1 and iterate from 1 to number. For each iteration, we multiply the current factorial with the iterator i and update the factorial.

Using While Loop to find the Factorial of a Number in C Programming

Another popular loop in C programming is the 'while' loop. Let's see how we can leverage the 'while' loop to find the factorial of a number.

#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;
}

In the 'while' loop, we decrement the number in every iteration until it is greater than 1. Meanwhile, we multiply factorial with a number.

Method - 2: Factorial Program using Recursive Solution

In recursive solutions, a function calls itself until a base condition is met. Recursive methods can be handy for solving problems such as finding the factorial of a number.

Using Recursion to find the Factorial of a number in C Programming

Here is how we can find the factorial of a number in C using recursion.

#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;
}

In the above code, the factorial function calls itself with number-1 until the number is greater or equal to 1. For each recursive call, the function returns the product of the number and factorial(number-1). If the number is less than 1, it returns 1, which is the base case for factorial calculation.

Using Ternary Operator to find the Factorial of a number in C Programming

A ternary operator can be used to find the factorial of a number using a recursive method. It works as a short form for an 'if-else' statement.

#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;
}

In this code, the ternary operator checks if the number is greater than or equal to 1; if true, it returns the product of the number and factorial(number-1); otherwise, it returns 1.

Factorial Program in C using tgamma() Method

In C, the tgamma function provides the Gamma function, which is essentially (number-1)!. We can use this function to easily calculate factorials.

#include <stdio.h>
#include <math.h>

int main() {
    int number;

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

    printf("Factorial of %d is: %.0f", number, tgamma(number + 1));
    return 0;
}

In the code above, we prompt the user to enter a number, read it using scanf(), and then calculate the factorial using tgamma(number + 1). The tgamma() function is applied to (number + 1) to calculate the factorial of a number. The result is then printed using printf().

Factorial Program in C using Functions

We can define a separate function for calculating factorial and call this function whenever we need to find the factorial of a number in C using function.

#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);

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

In this code, we have a separate function factorial, which calculates and returns the factorial of the given number.

C Program to Find Factorial of a Number using Pointers

Pointers in C can also be used to calculate the factorial of a number. Here's how you can do it:

#include<stdio.h>

void factorial(int number, long int *fact) {
   *fact = 1;
   
   for(int i = 1; i <= number; i++) {
      *fact = *fact * i;
   }
}

int main() {
    int number;
    long int fact;

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

    factorial(number, &fact);

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

In this code, we pass a pointer fact to the factorial function. Inside the function, we calculate the factorial and update the value pointed by the fact pointer.

Conclusion

There are multiple methods to calculate the factorial of a number in C. Whether it's using an iterative solution, recursion, the tgamma() method, or pointers, the most suitable method will depend on the specific needs of your program. It's a good idea to be familiar with each approach as they all reinforce key concepts in C programming.

FAQs

1. What is the time complexity of the factorial function using recursion?

The time complexity of the factorial function implemented using recursion is linear, denoted as O(n). This is because the function makes n recursive calls, each of which involves a constant amount of work.

2. Why is the initial value of 'factorial' set to 1 in the for loop and while loop examples?

The initial value of 'factorial' is set to 1 because the factorial of 0 is 1, and multiplication with 0 would result in the factorial being 0 for all numbers.

3. What is the purpose of the 'tgamma()' function in C?

The 'tgamma()' function in C returns the gamma function of a number. For positive integers, the gamma function of a number is equal to the factorial of (number-1). We add 1 to our number before passing it to 'tgamma()' to find the factorial.

4. Is there a difference in performance between the iterative and recursive solutions for finding the factorial of a number in C?

Yes, the recursive solution can be slower and more memory-intensive than the iterative one, especially for large input values. This is because each recursive call adds a new layer to the system's call stack. In comparison, the iterative solution only requires a single loop and does not add to the call stack.

5. How to write a factorial program in C using a for loop?

You can use a simple for loop to calculate factorials in C. The loop multiplies values from 1 to n:

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

This is the most common and beginner-friendly method for finding the factorial of a number.

6. How to write a recursive factorial program in C?

A recursive function calls itself until a base condition is met. Here's how you calculate factorial using recursion:

int factorial(int n) {
    if(n == 0) return 1;
    return n * factorial(n - 1);
}

This method demonstrates how C handles function calls and recursion depth.

7. Can you write a factorial program in C using a while loop?

Yes, a while loop can be used similarly to a for loop:

int fact = 1, i = 1;
while(i <= n) {
    fact *= i;
    i++;
}

This iterative method avoids recursion and is memory efficient for large input values.

8. How to write a factorial program in C using a function?

Encapsulate the logic in a reusable function:

int factorial(int n) {
    int result = 1;
    for(int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

Call factorial(n) in main() to compute and display the result.

9. What does a factorial program using pointers in C look like?

You can pass a pointer to a function that updates the result directly:

void factorial(int n, int *res) {
    *res = 1;
    for(int i = 1; i <= n; i++) {
        *res *= i;
    }
}

This method helps practice pointer handling and parameter passing in C.

10. How can I find factorial of a number in C using ternary operator?

A ternary operator can simplify recursive logic into a one-liner:


int factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

This compact version is functionally identical to a recursive approach.

11. How to use tgamma() to find factorial in C?

C’s math.h library includes tgamma() which returns the factorial of n - 1. To get n!, use:

#include <math.h>
double fact = tgamma(n + 1);

It’s efficient for floating-point numbers and large values but not ideal for teaching logic.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.