Creating a C program to find factorial of a number can be accomplished through various methods, including recursion, using functions, while loops, pointers, and if-else statements. Let’s explore each of these methods in detail.
Table of Contents
C Program to Find Factorial using Recursion
Recursion involves a function calling itself. In calculating a factorial, it’s a natural fit as factorial(n) can be defined as n * factorial(n-1).
#include <stdio.h>
long factorial(int n) {
if (n == 0) // Base case
return 1;
else
return (n * factorial(n - 1)); // Recursive call
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
printf("Factorial of %d = %ld\n", number, factorial(number));
return 0;
}
Find Factorial Using Function in C
#include <stdio.h>
long factorial(int n) {
long result = 1;
for(int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
printf("Factorial of %d = %ld\n", number, factorial(number));
return 0;
}
C Program to Find Factorial Using While Loop
Instead of a for
loop, a while
loop can be used for the same iterative approach.
#include <stdio.h>
long factorial(int n) {
long result = 1;
while (n > 1) {
result *= n;
n--;
}
return result;
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
printf("Factorial of %d = %ld\n", number, factorial(number));
return 0;
}
C Program to Find Factorial Using Pointers
Using pointers adds an additional layer of complexity. Here, the result is stored in a variable whose address is passed to the function.
#include <stdio.h>
void factorial(int n, long *result) {
*result = 1;
for(int i = 1; i <= n; ++i) {
*result *= i;
}
}
int main() {
int number;
long result;
printf("Enter a positive integer: ");
scanf("%d", &number);
factorial(number, &result);
printf("Factorial of %d = %ld\n", number, result);
return 0;
}
C Program to Find Factorial Using If-Else
This is a more basic approach, typically suitable for beginners, employing simple control flow.
#include <stdio.h>
long factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
printf("Factorial of %d = %ld\n", number, factorial(number));
return 0;
}
Each method has its merits and suitability depending on the program’s context and specific program requirements or the programmer’s preference. Recursion is elegant but can be less efficient for large numbers. Iterative solutions (function, while loop) are generally more efficient.
Pointers can be useful in specific contexts, especially when dealing with large data or system programming. The if-else method is straightforward and ideal for teaching basic programming concepts.