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 x 4 x 3 x 2 x 1 = 120
To illustrate the application of factorials, we will look at permutations, combinations, and probabilities. It is also used in computer science, such as algorithms, recursive functions, and programming problems to solve mathematic problems. In this article, we take a closer look at a factorial program in C.
What is a Factorial Program in C?
In the C language factorial program, you write code to perform the long multiplication required to find the factorial. In C, it can be done using techniques such as loops and recursion. When you use a loop, it does the iteration by going through numbers and multiplying them until the factorial is reached. In a recursive approach, the program breaks down the problem into minor problems.
The algorithms also involve the declaration of the data types in C that the variable can hold. Several data types exist, such as int, float, char, and double. It is essential to declare these to store the given numbers. Next, operators are used in the C code for factorial. Arithmetic operators are used to perform multiplication operations to find the factorial. Finally, the if, else statement, for and while loops are used to calculate the factorial through iteration.
Algorithm for Factorial Program in C
Here’s a general C program to find the factorial of a number:
- Begin the program.
- Define variables to hold the number entered by the user and the resulting factorial.
- Display a message asking the user to provide a number.
- Accept the input from the user.
- Initialise the variable by storing the factorial result in 1.
- Implement a loop (like a for or while loop) to run from 1 to the user’s number.
- Within the loop, update the factorial result by multiplying it with the current loop counter.
- Once the loop finishes, the factorial result will contain the desired value.
- Output the calculated factorial.
- Conclude the program.
Now let’s take a look at some examples of how to use a factorial program in c:
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 multiples the result variable by the loop counter at each step. This process continues from 1 to the input number until it produces the factorial value.
The program for factorial in C language using For loop looks like this:
// 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
Factorial Program Using While Loop
A factorial program in C uses a while loop to repeatedly multiply numbers from 1 up to the given input. The loop then runs as long as the counter is less than or equal to the input number. Each iteration updates the factorial result, which makes it an effective way to calculate factorials iteratively.
The C factorial program using a while loop looks like this:
#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;
}
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. This base case defines the stopping condition.
The flow chart below describes how it works:
In the recursive factorial C program below, the factorial function keeps calling itself with a 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, which is the base case for the calculation.
#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;
}
Factorial Program in C Using Arrays
A factorial program in C can also utilise arrays to handle large numbers. Arrays store individual digits of the factorial result. This enables calculations beyond standard integer limits. Multiplication is performed digit by digit, and results are stored in the array. This approach works well for computing factorials of very large numbers.
#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;
}
Factorial Program in C Using Ternary Operator
A factorial program in C can be designed within a minimum number of statements by using the ternary operator. The ternary operator actually behaves as a least one function checking whether the number is less than or equal to one, in which the base case is 1. Otherwise, known as recurrence, it multiplies the number by the factorial of one less number recursively.
Here is an example code:
#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;
}
Factorial Program to Find Factorial Series in C
The factorial series program calculates the factorials of given numbers up to 1. Within the program another loop or recursion is used to calculate the factorials of the numbers and then store them into a sequence.
The code is as follows:
#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;
}
Conclusion
Writing a program in C for factoring a number is as useful as any initial program that an applicant tries to tackle in an interview; it provides good knowledge and strengthens problem-solving skills. It is easy to use to appreciate various control structures such as conditional statements, loops, and recursive functions. 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.
Develop Industry-Relevant Skills While in College to Crack Your Placement!
Explore ProgramFrequently Asked Questions
1. 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.
2. 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.
3. 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.
4. 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. The recursion calls the function within itself. Both methods yield the same result but use different approaches.
5. 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.