hi guys,
I'm reaching to recursive function. Trying to digest such abstract concept.
I'm doing couple examples in order to see how recursive func. work and how to come up with the recursion
One example is this: use recursion to print out
123456789
then modify the function to print out
123456789987654321
Code:
#include <iostream>
#include <iomanip>
using namespace std;
void printNum(int ENDnum, int INITnum);
int main()
{
int end;
cout << "where to end: ";
cin >> end;
cout << endl;
printNum(end, 1);
return 0;
}
void printNum(int ENDnum, int INITnum)
{
cout << INITnum << setw(2);
if (INITnum < ENDnum)
printNum(ENDnum, INITnum+1);
cout << INITnum << setw(2);
}
I got the first part okay, but the 2nd part is quite confusing as I got hints from a friend.
Please correct me if my understanding is wrong
- when printNum is called for the first time --> print out "1" --> call itself again printNum(9, 1+1) --> print out "2" --> so on so forth
- as the func. reaches 8 --> print out "8" --> call itself printNum(9, 8+1) --> print out 9 --> "if" statement failed, for 9 < 9 is FALSE --> print out INITnum --> print out "9"
SHOULD THE FUNCTION STOP RECURSING RIGHT THERE?
thus the out should ONLY be 1234567899 ?
yet it's 123456789987654321
any insight will be great!!!!