#include<iostream>
void printIt(int n);
void print(int a);
usingnamespace std;
int main() {
int n;
cout<<"\nEnter a number: \n";
cin >> n;
cout<<" \tWhat is printed on Function [printIt]: \n" ;
printIt(n);
cout<<endl <<endl;
cout<<"\tWhat is printed on Function [print]: \n";
print(5);
}
void printIt( int n )
{
if(n >= 2) // recursive case
printIt( n - 1 ); // recursive call
cout << n - 1 << endl;
}
void print(int a)
{
if (a >= 1)
{
cout<< a <<endl;
print(a - 1);
}
}
That was well explained. You make is look very easy, but when one is given a problem from the book to solve it using recursion. One does not see the recursion. There is a problem is the book by Malik to solve an an equation using recursion:
recursion can be tricky but if you think about it carefully, it works JUST LIKE everything else.
consider
long long factorial(unsigned int x)
{
if(x == 0 || x == 1)
return 1;
else
return factorial(x-1) * x;
}
if you put in 3, for example:
is 3 zero or 1?
no, call factorial(2).
is 2 zero or 1?
no, call factorial(1)
is it zero or 1? yes, return 1.
resume control after return statement, we are in factorial(2) now.
2*1 is 2, return it.
resume control after return statement, we are in factorial(3) now.
3*2 is 6, return it,
control returns back to the caller of factorial(3) (main, for example).
so what you are seeing is that it stops what it is doing, calls a function (that happens to be itself, but so what? its the same as if it called any other function, it stops what it is doing and hands control to the called function, that executes until it returns a result, and then it proceeds with the result where it left off. That the function that is called calls another function that calls another function chains this idea, and it is STILL irrelevant that the function called is itself. It works the same way had it called distinct functions or none at all. Each call stops where it is and hands control to the subroutine and waits for that to hand control back.
If you can get to that point, the the fact that it is recursive melts away ... because it works just like everything else.
unsignedint C( unsignedint n, unsignedint r )
{
if( n < r ) return 0 ; // C(n,r) == 0 if n < r (sanity check)
elseif( ( n == r ) || ( r == 0 ) ) return 1 ; // C(n,n) == 1 and C(n,0) == 1
// the recursion bottoms out
elsereturnC( n-1, r-1 ) + C( n-1, r ) ; // by Pascal's rule (recursive)
// https://en.wikipedia.org/wiki/Pascal%27s_rule
}