How to use recursion...
Jan 5, 2012 at 3:10pm UTC
Can someone please help me with recursion i have no clue how to use it and have never used recursion before
suppose you have a M by N grid how do you compute all squares that can be obtained from this grid using recursion?? Please explain in simple terms?
Jan 5, 2012 at 3:20pm UTC
Recursion is any function that calls itself. All it needs is a body and a termination condition.
For example, to count down from 5 to 0 recursively:
1 2 3 4 5
void countDown(int n) {
if (n == 0) { printf("%d!" , 0); return ; }
printf("%d... " , n);
countDown(n-1);
}
The termination condition (n == 0) makes sure it stops at some point, by quitting before doing another recursive call to countDown.
Jan 5, 2012 at 3:44pm UTC
So your code just prints n to 1? Hmmm... Looks good...
Please give me some time i will think abt how to do the given problem thanks a lot... :)
Jan 5, 2012 at 8:58pm UTC
An example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
using namespace std;
int factorial(int n) // 1, 1, 2, 6, 24, 120, 720, ...
{
if (n == 0) return 1;
return n * factorial(n-1);
}
main()
{
int n=7;
//cout << "Enter a non-negative integer: ";
//cin >> n;
cout << "The Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}
Topic archived. No new replies allowed.