Have you ever found yourself staring at a C programming assignment, wondering how to calculate the product of a series of numbers? If so, you’re not alone! One of the most common starting points for any coding enthusiast is writing a C Program For Factorials In C.
Whether you are a student trying to grasp the basics or someone preparing for technical interviews, understanding factorials is crucial. It’s not just about math; it’s about understanding how loops, recursion, and functions work in harmony. In this article, we are going to break down everything you need to know about factorials in C, explained in a simple, conversational way.
So, grab a cup of coffee, and let’s dive into the world of C programming!
What are Factorials in C?
Before we start typing code, we need to understand what we are actually calculating. In mathematics, the factorial of a non-negative integer is the product of all positive integers less than or equal to that number.
It sounds a bit mouthful, right? Let’s simplify it.
If you have a number, let’s say N, its factorial (represented as N!) is simply N multiplied by every whole number below it until you reach 1.
For example, let’s find the factorial of 7:
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
Here, 5040 is the factorial of 7.
The General Formula
The general formula to find the factorial of any number N is:
N! = N * (N-1) * (N-2) * (N-3) * ……. * 3 * 2 * 1
Some Important Examples
To make it crystal clear, here are a few quick examples:
- 0! = 1Â (This is a standard rule in math!)
- 1! = 1
- 2! = 2 * 1 = 2
- 3! = 3 * 2 * 1 = 6
- 4! = 4 * 3 * 2 * 1 = 24
Factorials are super useful in real-world scenarios, especially in permutations and combinations (basically counting how many ways you can arrange things). Now that we know the math, let’s see how to teach a computer to do it.
Factorials in C Problem Statement
Here is the problem we are trying to solve today:
Problem: Given a number N, write a program to find the factorial of N.
Seems simple, right? In the C language, we can approach this in a few different ways. We aren’t just going to show you one way; we are going to explore the three most popular methods:
- Using Loops (The Iterative Approach)
- Using Recursion (The “Function Calling Itself” Approach)
- Using Functions (The Modular Approach)
We will walk through each method, look at the code, and understand how it works.
Finding Factorials in C: The Logic

Let’s quickly discuss the algorithm before we jump into the actual coding. Writing code without understanding the logic is like building a house without a blueprint!
Here is the step-by-step logic (Pseudocode) to find the factorial of a positive number:
- Start the program.
- Declare variables: We need one variable for the input number (let’s call itÂ
n) and one to store the result (factorial). - Read Input: Ask the user to type the number and store it inÂ
n. - Initialize Result: SetÂ
factorial to 1. (Why 1? Because if we set it to 0, the final multiplication result would be 0!) - The Loop: Repeat a process as long asÂ
n is greater than 1.- MultiplyÂ
factorial byÂn. - DecreaseÂ
n by 1.
- MultiplyÂ
- Print Result: Once the loop finishes, display theÂ
factorial. - End the program.

Factorials In C Using Loops
The most common way to solve this problem is by using loops. Specifically, a for loop or a while loop works perfectly here. This method is called the Iterative Method.
In this approach, we make the computer iterate through all numbers from 1 to N, multiplying them one by one.
The Code: Factorial in C using Loops
Here is a standard C program to find the factorial using a for loop.
C#include<stdio.h>
int main() {
int i, fact = 1, number; // Declare variables
printf("Enter a number: ");
scanf("%d", &number); // Read the number from user
// Loop starts from 1 and goes up to the user's number
for(i = 1; i <= number; i++) {
fact = fact * i; // Multiply current value of fact by i
}
printf("Factorial of %d is: %d", number, fact);
return 0;
}

How Does This Work?
- We initializeÂ
fact to 1. - If the user enters 5, the loop runs 5 times.
- Iteration 1:Â
fact becomes 1 * 1 = 1 - Iteration 2:Â
fact becomes 1 * 2 = 2 - Iteration 3:Â
fact becomes 2 * 3 = 6 - Iteration 4:Â
fact becomes 6 * 4 = 24 - Iteration 5:Â
fact becomes 24 * 5 = 120 - The loop ends, and we print 120.
Output
textEnter a number: 5
Factorial of 5 is: 120
Time and Space Complexity Using Loops
When analyzing code efficiency, we look at Time and Space Complexity.
- Time Complexity: O(N)
Since the loop runs exactly N times (where N is the input number), the time taken grows linearly with the input size. If you input 100, it runs 100 times. - Space Complexity: O(1)
We are only using a few variables (i,Âfact,Ânumber) regardless of how big the input number is. The memory usage stays constant. This makes the loop method very memory efficient!
Factorials in C Using Recursion
Now, let’s get a little fancy. Have you ever heard of recursion? It’s a technique where a function calls itself to solve a smaller version of the problem.
Think of it like standing between two mirrors. You see a reflection of a reflection, going on forever (until the glass ends). In programming, we need a “stop” signal, otherwise, the program will crash. This is called the Base Condition.
The Logic
For factorial, the logic is:
factorial(n) = n * factorial(n-1)
The base condition is when n = 1, we return 1.
The Code: Factorial in C using Recursion
C#include <stdio.h>
// Recursive function definition
unsigned int factorial(unsigned int n) {
// Base condition: if n is 0 or 1, return 1
if (n == 1 || n == 0) {
return 1;
}
// Recursive call: n multiplied by factorial of (n-1)
return n * factorial(n - 1);
}
// Driver code (The main function)
int main() {
int num = 7;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
How Does This Work?
Let’s trace factorial(3):
factorial(3) callsÂ3 * factorial(2)factorial(2) callsÂ2 * factorial(1)factorial(1) hits the base condition and returns 1.- Now it goes back up:Â
factorial(2)Â becomesÂ2 * 1 = 2. factorial(3)Â becomesÂ3 * 2 = 6.
Output
textFactorial of 7 is 5040
Time and Space Complexity Using Recursion
- Time Complexity: O(N)
Just like the loop, the function is called N times. - Space Complexity: O(N)
Unlike the loop, recursion uses stack memory. Every time the function calls itself, the computer needs to remember the previous state. If you input 1000, you might get a “Stack Overflow” error because the memory runs out. This is why loops are generally safer for very large numbers in C.
Factorial Of A Number Using Function In C
Writing all the logic inside the main function is okay for small programs, but it’s bad practice for big projects. It makes your code messy. A better approach is Modular Programming—breaking the code into smaller, reusable functions.
In this method, we create a separate function (say findFactorial) that handles the calculation. The main function just handles the input and output.
The Code: Factorial using Function
C#include<stdio.h>
// Function prototype
int findFactorial(int n);
int main() {
int n, fact;
printf("Enter a number to get factorial: ");
scanf("%d", &n);
// Calling the function
fact = findFactorial(n);
printf("Factorial of %d is: %d", n, fact);
return 0;
}
// Function definition
int findFactorial(int n) {
int i, fact = 1;
// Using a loop inside the function
for(i = 1; i <= n; i++) {
fact = fact * i;
}
return fact;
}
Why is this better?
Notice how clean the main function looks? We can use the findFactorial function anywhere else in our program without rewriting the logic. It keeps our code organized and readable.
Output
textEnter a number to get factorial: 7
Factorial of 7 is 5040
Become A C Developer With Kaashiv Infotech
Looking to dive into the world of embedded systems and low-level programming and carve your path to success? Kaashiv Infotech is here for you! Our Comprehensive C Programming Inplant Training (IPT) and Certification Course is specially designed by industry veterans to equip you with practical skills and real-world experience that will help you to set your foot in the competitive C development and IoT industry.
Let’s break down our training offerings to see what makes our program stand out
- Live Industry Projects + Capstone: You’ll work on 2 real-time industry projects to build a solid portfolio and enhance your learning with a capstone project that showcases your proficiency in core C programming.
- Daily Coding Drills:Â Get hands-on practice with daily coding exercises that enhance your retention and help you master syntax, memory management, and pointers.
- Expert Doubt Resolution:Â Our regular mentor sessions ensure that no concept goes unanswered, giving you clarity of complex logic and architecture.
- Advanced Development Lab:Â Access our exclusive virtual labs for system-level coding practice and polish your debugging skills in a controlled, professional environment.
- Industry-Oriented Syllabus:Â Learn industry-relevant techniques and best practices that are directly applicable to real-world embedded scenarios.
- Triple Certification:Â Earn a comprehensive credential upon completion, including an Internship Certificate, IPT Certificate, and Industrial Exposure Certificate valued by employers.
- Peer Collaboration Network:Â Engage with fellow batchmates and mentors in our community forum to exchange ideas, seek advice, and collaborate on codebases.
- MVP-Guided Sessions:Â Benefit from interactive sessions led by experienced instructors, including Microsoft MVPs and Google-recognized experts who guide you every step of the way.
- Mock Interview & Prep:Â Gain access to curated interview opportunities, technical assessments, and a dedicated question bank to help you land your dream job in development.
- 100% Job Assistance + Career Resources: We’re offering 100% job assistance along with ATS-friendly resume tools and career guidance to help you secure employment immediately after graduation.
So what are you waiting for? Launch your career with confidence! Join the Kaashiv Infotech C Programming & IPT Course and unlock your potential today.
Conclusion
And there you have it! We’ve covered the A to Z of writing a C Program For Factorials In C. We started with the basic mathematical definition, moved on to the iterative method using loops (which is super efficient for memory), explored the elegant but memory-heavy recursive method, and finally looked at how to structure our code professionally using functions.
Learning these fundamental concepts is the first step to becoming a proficient programmer. Whether you choose loops or recursion depends on the specific problem you are trying to solve, but understanding both gives you the tools to make the right decision.
Keep practicing, try changing the code (maybe use a while loop instead of a for loop), and see what happens. Happy coding!
Frequently Asked Questions (FAQs)
1. How can we find the factorial of a number using the C language?
There are three primary methods to find the factorial of a number in C: using iterative loops (like for or while), using recursion (where a function calls itself), and by creating separate user-defined functions to handle the logic.
2. What is the factorial of 0?
The factorial of 0 is 1.
Mathematically, 0! = 1. This is a standard definition used to ensure the formulas for permutations and combinations work correctly. Our C programs must handle this case, usually by initializing the result variable to 1.
3. What is the difference between recursion and iteration for finding factorials?
The main difference lies in memory usage. Iteration (loops) uses a constant amount of memory (O(1)), making it efficient for large inputs. Recursion uses stack memory which grows with the input size (O(N)), meaning it can lead to a stack overflow error if the number is too large.
4. Why does my factorial program return a weird number (like a negative value) for large inputs?
This happens because of Integer Overflow. The factorial grows very quickly. A standard int variable in C can only hold values up to a certain limit (usually 2,147,483,647). 13! exceeds this limit. To fix this, you can use unsigned long long or double data types to hold larger numbers.
5. What is the time complexity of a factorial program in C?
For both the iterative approach (loops) and the recursive approach, the time complexity is O(N). This means the time taken to calculate the factorial increases linearly with the size of the number N.