-moz-user-select:none; -webkit-user-select:none; -khtml-user-select:none; -ms-user-select:none; user-select:none;

Thursday 11 June 2015

Finding factorial by recursion

As I have discussed in my previous blog that a function that repeats itself is called recursion.So, today I am here with  a very common example of recursion in C++. In this example, I will find the factorial of a given number by recursion.Below is the source code of this program.

Source code

  1. #include <iostream>
  2. using namespace std;

  3. int factorial(int);

  4. int main() {
  5.     int n;
  6.     cout<<"Enter a number: ";
  7.     cin>>n;
  8.     cout<<"Factorial="<<factorial(n);
  9.     return 0;
  10. }

  11. int factorial(int n) {
  12.     if (n>1) {
  13.         return n*factorial(n-1);
  14.     }
  15.     else {
  16.         return 1;
  17.     }
  18. }

Output

C++,programming,recursion,khgamujtaba,factorial

Explanation
Suppose user enters 4 which is passed to function factorial(). Here are the steps involved:
  • In first factorial() function, test expression inside if statement is true. The statement return num*factorial(num-1); is executed, which calls second factorial() function and argument passed is num-1 which is 3.
  • In second factorial() function, test expression inside if statement is true. The statementreturn num*factorial(num-1); is executed, which calls third factorial() function and argument passed is num-1 which is 2.
  • In third factorial() function, test expression inside if statement is true. The statement return num*factorial(num-1); is executed, which calls fourth factorial() function and argument passed is num-1 which is 1.
  • The fourth factorial() function, test expression inside if statement is false. The statementreturn 1; is executed, which returns 1 to third factorial() function.
  • The thrid factorial() function returns 2 to second factorial() function.
  • The second factorial() function returns 6 to first factorial() function.
  • Finally, first factorial() function returns 24 to the main() function and is displayed.        ( The above reference has been taken from www.programiz.com)

No comments:

Post a Comment