Thursday, 5 June 2014
0
C Program 14: To Find The Factorial of a Number Using Recursion
Aim: To find the factorial using recursion.
What is Recursion? when a function calls itself, the phenomenon is referred to as recursion and it is one of the most powerful features of C. Most of the algorithms that are developed using C use recursion.
Code:
// To find the factorial of a given number using recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int fact, a;
printf("Enter the number: ");
scanf("%d", &a);
fact=factorial (a);
printf("The factorial of the given number is: %d\n", fact);
getch();
}
int factorial(int x)
{
int f;
if (x==1)
{
return(1);
}
else
{
f=x*factorial(x-1); //using recursion
}
return f;
}
The real part is in the function factorial. The function takes x as a parameter which is the number whose factorial we want to find. Say, we want to find 4! that means x would be equal to 4.
Now, we would use if else statement. If the value of x is 1, the function would return 1.
Else, the following formula would be used:
f=x*factorial(x-1);
Note that we are using the same function once again. We are using factorial() inside factorial(). This is RECURSION.
But this time the value passed to the function isn't 4. It is 3 i.e. 4-1
thus, on successive calls the function would call itself and pass parameters like - 4,3,2,1. When function has 1 as parameter, if statement would be executed and control would return to the second last function i.e. the one with parameter 2.
Thus, we would get 4*3*2*1 = 24
What is Recursion? when a function calls itself, the phenomenon is referred to as recursion and it is one of the most powerful features of C. Most of the algorithms that are developed using C use recursion.
Code:
// To find the factorial of a given number using recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int fact, a;
printf("Enter the number: ");
scanf("%d", &a);
fact=factorial (a);
printf("The factorial of the given number is: %d\n", fact);
getch();
}
int factorial(int x)
{
int f;
if (x==1)
{
return(1);
}
else
{
f=x*factorial(x-1); //using recursion
}
return f;
}
Now, we would use if else statement. If the value of x is 1, the function would return 1.
Else, the following formula would be used:
f=x*factorial(x-1);
Note that we are using the same function once again. We are using factorial() inside factorial(). This is RECURSION.
But this time the value passed to the function isn't 4. It is 3 i.e. 4-1
thus, on successive calls the function would call itself and pass parameters like - 4,3,2,1. When function has 1 as parameter, if statement would be executed and control would return to the second last function i.e. the one with parameter 2.
Thus, we would get 4*3*2*1 = 24
Subscribe to:
Post Comments (Atom)
0 Responses to “C Program 14: To Find The Factorial of a Number Using Recursion”
Post a Comment