Factorial Programs in C β A Step-by-Step Guide
In this article, we will discuss how to calculate the factorial programming in c using three different methods: For Loops, Recursion, and While Loop.
A factorial is a mathematical operation that returns the product of all positive integers less than or equal to a given positive integer. The symbol for factorial is β!β, and the notation for the factorial of a number n is βn!β. For example, the factorial of 5 is 5! = 5 x 4 x 3 x 2 x 1 = 120. In this article, we will discuss how to calculate factorial using three straightforward methods. We will be covering the following sections today:
So, without further ado, letβs get started!
Using For Loop
This is the most basic method for calculating a number's factorial. A for loop iterates through the numbers from 1 to the given number, and the product of all the numbers is calculated and stored in a variable. This variable is then returned as the final factorial value.
Also Read: Do While Loop
Letβs look at a step-by-step guide for calculating the factorial of a number using a for loop in C programming.
1: Include the necessary libraries
The first step in any C program is to include the necessary libraries. For this program, we will only need the stdio.h library, which is used for input and output operations. To include this library, we will use the #include pre-processor directive at the top of our program, like this:
#include <stdio.h>
Also Read: Storage Class in C
2: Define the factorial function.
The next step is to define a function called factorial() that takes an integer argument n. This function will be used to calculate the factorial of a given number.
int factorial(int n) { // code to calculate factorial goes here}
Also Read: Difference Between Compiler and Interpreter
3: Initialize the result variable.
Inside the factorial() function, we will create a variable called result and initialize it to 1. This variable will store the final result of the factorial calculation.
int factorial(int n) { int result = 1; // code to calculate factorial goes here}
Also Read: Pointers in C
4: Use a for loop to iterate through the numbers.
To calculate the factorial, we will use a for loop to iterate through the numbers from 1 to n. In each iteration, we will multiply the current value of result by the loop variable, and store the result back in result. This will give us the product of all the numbers from 1 to n, which is the factorial.
int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result = result * i; } // code to return result goes here}
Also Read: While loop in C
5: Return the result.
After the loop completes, we will return the value of result as the final factorial value.
int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result = result * i; } return result;}
Also Read: Token in C Programming
6: Get input from the user.
In the main function, we will declare a variable to hold the input value, and use the scanf() function to read the value from the user.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); // code to call factorial function goes here}
Also Read: Arrays in C Programming
7: Call the factorial function.
We will pass the input value to the factorial() function and store the result in a variable.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); // code to print result}
Also Read: Circular Linked List
8: Print the result to the user.
Finally, we will use the printf() function to print the final result to the user.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); printf("The factorial of %d is %d", input, result); return 0;}
Below is the complete code for the program:
#include <stdio.h>
int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result = result * i; } return result;}
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); printf("The factorial of %d is %d", input, result); return 0;}
Output:
This program prompts the user to enter a number, calculates the factorial of that number using the for loop method, and then prints the result to the user.
It is important to note that for large numbers, the factorial can result in a very large number and may cause overflow or result in an inaccurate value.
Best-suited C / C++ courses for you
Learn C / C++ with these high-rated online courses
Using Recursion
In this method, the factorial function calls itself repeatedly with the input value decremented by 1, until the base case of 1 is reached. The result is then returned to the previous call, and so on, until the final result is obtained. This method is also known as a recursive factorial function.
Letβs look at a step-by-step guide for calculating the factorial of a number using recursion in C programming.
1: Include the necessary libraries.
#include <stdio.h>
Also Read: Linked List Example in C and Python
2: Define the factorial function.
int factorial(int n) { // code to calculate factorial goes here}
Also Read: Introduction to Linked List Data Structure
3: Define the base case.
In the factorial function, we will define the base case which is the stopping point of the recursion. The base case is defined as the point where the recursion stops. In this case, when the input value is 1, the function will return 1, which is the factorial of 1.
int factorial(int n) { if (n == 1) { return 1; } // code to calculate factorial goes here}
Also Read: Doubly Linked List
4: Define the recursive case.
In the recursive case, we will call the factorial function again, but this time with the input value decremented by 1. The result of this call will be multiplied by the current input value and stored in a variable.
int factorial(int n) { if (n == 1) { return 1; } int result = factorial(n-1) * n; return result;}
Also Read: Singly Linked List
5: Get input from the user.
In the main function, we will declare a variable to hold the input value, and use the scanf() function to read the value from the user.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); // code to call factorial function goes here}
Also Read: Selection Sort Algorithm
6: Call the factorial function.
We will pass the input value to the factorial() function and store the result in a variable.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); // code to print result goes here}
Also Read: QuickSort Algorithm
7: Print the result to the user.
Finally, we will use the printf() function to print the final result to the user.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); printf("The factorial of %d is %d", input, result);
return 0; }
Below is the complete code for the program:
#include <stdio.h>
int factorial(int n) {if (n == 1) {return 1;}int result = factorial(n-1) * n;return result;}
int main() {int input;printf("Enter a number: ");scanf("%d", &input);int result = factorial(input);printf("The factorial of %d is %d", input, result);return 0;}
Output:
This program prompts the user to enter a number, calculates the factorial of that number using the recursion method, and then prints the result to the user.
It is important to note that recursion can take up more memory than a loop, and if not implemented correctly, it can cause a stack overflow error. It is important to have a well-defined base case and to make sure that the recursive case moves towards the base case.
Using recursion is a powerful method to calculate the factorial of a number in C programming. It is an elegant and optimized solution, but it is also important to consider the limitations of this method and choose the one that best suits your needs.
Using While Loop
This method is similar to the for loop method, but uses a while loop instead. A variable is initialized to 1, and the while loop iterates until the input value is reached. In each iteration, the variable is multiplied by the loop variable, and the result is stored in the variable.
Letβs look at a step-by-step guide for calculating the factorial of a number using a while loop in C programming.
1: Include the necessary libraries.
#include <stdio.h>
2: Define the factorial function.
int factorial(int n) { // code to calculate factorial goes here}
3: Initialize the result variable.
Inside the factorial() function, we will create a variable called result and initialize it to 1. This variable will store the final result of the factorial calculation.
int factorial(int n) { int result = 1; // code to calculate factorial goes here}
4: Use the while loop to iterate through the numbers.
To calculate the factorial, we will use a while loop to iterate through the numbers from 1 to n. In each iteration, we will multiply the current value of result by the loop variable, and store the result back in result. This will give us the product of all the numbers from 1 to n, which is the factorial.
int factorial(int n) { int result = 1; int i = 1; while(i <= n) { result = result * i; i++; } return result;}
5: Get input from the user.
In the main function, we will declare a variable to hold the input value, and use the scanf() function to read the value from the user.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); // code to call factorial function goes here}
6: Call the factorial function.
We will pass the input value to the factorial() function and store the result in a variable.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); // code to print result goes here}
7: Print the result to the user.
Finally, we will use the printf() function to print the final result to the user.
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); printf("The factorial of %d is %d", input, result); return 0;}
Below is the complete code for the program:
#include <stdio.h>
int factorial(int n) { int result = 1; int i = 1; while(i <= n) { result = result * i; i++; } return result;}
int main() { int input; printf("Enter a number: "); scanf("%d", &input); int result = factorial(input); printf("The factorial of %d is %d", input, result); return 0;}
Output:
This program prompts the user to enter a number, calculates the factorial of that number using the while loop method, and then prints the result to the user.
Using a while loop method can be useful when you need to check a condition before or after the execution of the loop.
Endnotes
Hope this article was helpful for you to understand different methods to calculate a factorial in the C programming language. Explore our C articles to find out more about the language and consolidate your knowledge of the fundamentals.
Contributed By: Prerna Singh
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio