let us now see a simple example of recursion. Suppose we want to calculate the factorial value of an integer. As we know, the factorial of a number is the product of all the integers between 1 and that number.
For example, 4 factorial is 4*3*2*1. This can also be expressed as 4!=4*! where '!' stands for factorial. Thus factorial of a number can be expressed in the form of itself. Hence, before we try to write a recursive function for calculating factorial let us take a look at the non-recursive function for calculating the factorial value of an integer.
Program
#include<stdio.h>
#include<conio.h>
nt factorial(int )
int main( )
{
int a, fact;
printf("enter any number");
scanf("%d",&a);
fact=factorial(a);
printf("factorialValue=%d\n",fact);
return 0;
}
int factorial(int x)
{
int f=1,i;
for (i=x;i>=1;i--)
f=f*i;
return (f);
}
And here is the output...
enter any number 3
factorial value= 6

No comments:
Post a Comment
theengineerschoice01@gmail.com