Tuesday, April 30, 2013

c Program to Find Factorial of a Number using Recursion

 Program to Find Factorial of a Number using Recursion
What is Recursion in C Program :
Recursion refers to Calling the function again and again inside the body of any Program by the Same Function. In other words, It refers to thinking and then solving the problem. For Each Call of a function, the Program computes better result.

With Recursion , The Problem in C Programming can be reduced in each function call till the base value or result is reached beyond which no Call can be made or no more better result can be obtained.
Factorial of a Number :
Factorial of any number which should be non negative is equal to Product of all the integers less than or equal to that particular number. It is denoted by n! where n is any positive number and its factorial will be equal to :
n!=n*(n-1)*(n-2)*(n-3)... and so on till integer value 1 comes.
Let us take the example of 5! . It will be equal to 5*4*3*2*1 => 120 .
0! according to number systems is treated as 1. In this program, we shall use Recursion technique to find the Factorial of any positive number. Copy the Source code and save it as *.c . Compile and run thereafter the C Program.
#include <stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
getch();
}
long fact(int n)
{
int m;
if (n == 1)
return n;
else
{
m = n * fact(n-1);
return m;
}
}

Recursion refers to a method which solves a problem by solving a smaller version of the problem and then using that result plus some other computation to formulate the answer to the original problem. Often times, in the process of solving the smaller version, the method will solve a yet smaller version of the problem, and so on, until it reaches a "base case" which is trivial to solve.

No comments:

Post a Comment