Recursion can be used instead of looping statements to find the factorial of a number. Recursion can be defined in simple terms as a function calling itself. Factorial of a number is the product of all numbers from 1 to the number itself. Example: Factorial 5 written as 5! = 5*4*3*2*1 = 120. Here let us see a simple program that uses recursion to find the factorial of a number. I will be using C++ syntax, but you may take the logic and change the syntax to suit any programming language. In some programming languages, you might get a stack overflow error if you use too much recursion.
Code
The above function is a recursive function, that is it has a function call to itself in its body. The code is self explanatory and the logic is simple. Try to review the process by taking an example and going through the process one by one.
Code
int factorial(n)
{
if(n==1)
return n;
else
return (n * factorial(n-1));
}
cout<<factorial(5);
The above function is a recursive function, that is it has a function call to itself in its body. The code is self explanatory and the logic is simple. Try to review the process by taking an example and going through the process one by one.
No comments:
Post a Comment