C program to find factorial of a number using Recursion
What does the term "Factorial of a Number" mean?
In mathematics, factorial is the product of all positive integers that are less than or equal to a certain positive integer, and it is symbolised by that positive integer and an exclamation point. So, factorial seven is represented as 9!, which equals 9*8*7*6*5*4*3*2*1. Factorial 0 is equal to 1 in mathematics.
Example:
12! =12*11*10*9*8*7*6*5*4*3*2*1
17! =17*16*15*14*13*12*11*10*9*8*7*6*5*4*3*2*1
To find factorial of a given number in C, there are two ways:
- Using Recursion
- Using Loop
Factorial of a Number using Recursion:
This code asks the user to enter any integer number, calculates its factorial, and displays the results on the screen. To complete the work, we will utilize a recursive function which must be user defined. In order to determine the factorial of the input integer, the function "factorial" in this case calls itself recursively. The code includes user interaction, but if we don't want it, we can just provide an integer number to variable no and omit the scanf statement. In other words, we can change it as we like; the argument would remain the same in every situation.
Code:
// using recursion
#include<stdio.h>
long long int factorial ( long int no )
{
if ( no == 0 ) //check whether the condition is true or false
return 1; //if the number is zero it will return one
long long int fact = factorial ( no - 1 ); //storing the value of the recursive function in variable
return no * fact; //returning the value
}
int main()
{
long long int numb; //taking variable numb
long long int f; //taking variable f
printf("Enter a number: "); //put any integer number
scanf( "%ld", & numb) ; //value stores in numb variable
f = factorial ( numb ); //f stores the value of the factorial
printf( "%ld is the factorial of %ld\n", f, numb ); //printing the factorial value of a number
return 0;
}
Output: (If user puts 9 as input)
Enter a number: 9
362880 is the factorial of 9
Output: (If user puts 11 as input)
Enter a number: 11
39916800 is the factorial of 11
Note: Remember that we can not find factorial of a large number as the value will be so large to store.
C Program to find factorial of a given number using loop:
Code:
//using loop
#include<stdio.h>
int main()
{
long long int index, facto=1, no; //taking variables
printf("Enter a number: "); //asks user for a integer value
scanf("%ld", & no); //stores value in "no" variable
for (index = 1; index <= no; index ++) //using for loop
{
facto = facto * index; // logic
}
printf("%ld is the factorial of %ld\n", facto, no ); //printing the factorial value of given number
return 0;
}
Output: (If user puts 12 as input)
Enter a number: 12
479001600 is the factorial of 12
Output: (If user puts 4 as input)
Enter a number: 4
24 is the factorial of 4