Thursday, 31 October 2013

Program to find factorial of a number using Recursion

Recursion is one of the most awesome properties in the world of programming. It is used in many cases, but the most basic use of recursion is to find the factorial of a given number. There are many other ways to find the factorial, but the one which uses Recursion is the easiest. Recursion is the property in which a function calls itself inside its own body. This may be a hard to understand till you read the example.

Facorial : Consider an integer n. Factorial of n is denoted as n! and is found out by multiplying all numbers from 1 to n.
e.g.,
      1! = 1
      3! = 3 x 2 x 1  = 6
      5! = 5 x 4 x 3 x 2 x 1 = 120
    10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 3628800

Here is the code :
#include<iostream.h>
long Factorial(long a)
{
   if(a>1)
   {
       return (a*Factorial(a-1));
   }
   else
   {
       return 1;
   }
}
int main()
{
   long number;
   cout<<"Enter the number : ";
   cin>>number;
   cout<<endl<<number<<"! = "<<Factorial(number)<<endl;
   return 0;
}

For newer IDEs, visit this page.
Working

  • Suppose the input number is 1. The program outputs 1! = 1 since we have written an else statement specifically when the input is 1. 
  • Suppose the input number is 4. Upon function calling, the variable in which 4 is stored, number, is changed to the variable we have in the function definition, i.e., a. Since 4>1, the if statement is activated.
    The function returns 4 x (Factorial(4-1)), which is equal to 4 x (Factorial (3)) which is equal to 4 x Factorial ( 3 x Factorial (2)) and so on. This continues till 4 becomes decremented to 1. So the final expression is 4 x 3 x 2 x 1. Hence the output is 4! = 24. Since the function Factorial is again called inside the function Factorial, the function is said to undergo Recursion.

FUN FACT : If you search 'Recursion' on Google, it will say
Did you mean: Recursion?
(Try it out for yourself!) If you understand the joke, Kudos, because, you have understood recursion!

No comments:

Post a Comment

You might also like