Friday, April 18, 2014

Understand recursion in C++ programming



Recursion method is widely used in computer programming.  Sometimes it is confusing. In this video a, factorial example is used to study how recursion works in C++ programming.
Example code:
#include <iostream> 
using namespace std; 
int Factorial( int n)
{
int m;
cout<<"n="<<n<<endl;
if( n == 1)
return 1;
else {
  m = n * (Factorial(n-1));
  cout<<"m="<<m<<endl;
       return (m);
       }

int main() //n!=n*(n-1)*.....*2*1

     cout<<"result="<<Factorial(4)<<endl;
 }
Output:
n=4
n=3
n=2
n=1
m=2
m=6
m=24
result=24
You can see
  cout<<"m="<<m<<endl;
is ignored before
m = n * (Factorial(n-1));
 recursion finished, Only n=4, 3,2, 1 are printed out.
After recursion finished,
 cout<<"m="<<m<<endl;
is printed from bottom to top.
Video: Understand recursion in C++ programming

No comments:

Post a Comment