So a friend of mine is taking one of his first CS classes and mentions that he's using recursion in his very first program. He sends me the code below. Right off the bat I noticed that he isn’t catching the return value of his recursive call and I assumed it wouldn’t work. But he insists that it does work so I try his program out, and to my surprise it functions exactly as expected. Ignoring the fact that this is a dumb way to get from point A to point B, why does this even work?
I was playing around with what he sent me and added a cout
after the if statement. Besides that, the first chunk of code and the second chunk are identical.
If I input the following for the first program, here's what I get...
Enter a Number: 10
You entered: 10 Is this correct? (Y/N): N
Enter a Number: 12
You entered: 12 Is this correct? (Y/N): Y
main() = 12
And then if I do the same thing with the second program, here's what I get...
Enter a Number: 10
You entered: 10 Is this correct? (Y/N): N
Enter a Number: 12
You entered: 12 Is this correct? (Y/N): Y
main() = 6300096
What's going on!?
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int getNum()
{
cout << "Enter a Number: ";
int x;
cin >> x;
cin.ignore(100, '\n');
while(x < 0) {
cout << "Please enter amount greater than 0: ";
cin >> x;
cin.ignore(100, '\n');
}
cout << "You entered: " << x << " Is this correct? (Y/N): ";
char response;
cin >> response;
cin.ignore(100, '\n');
if (response != 'Y') {
getNum();
} else {
return x;
}
}
int main() {
cout << "\nmain() = " << getNum() << endl;
return 0;
}
The only difference between the top and the bottom is a cout
statement after the if statement.
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int getNum()
{
cout << "Enter a Number: ";
int x;
cin >> x;
cin.ignore(100, '\n');
while(x < 0) {
cout << "Please enter amount greater than 0: ";
cin >> x;
cin.ignore(100, '\n');
}
cout << "You entered: " << x << " Is this correct? (Y/N): ";
char response;
cin >> response;
cin.ignore(100, '\n');
if (response != 'Y') {
getNum();
} else {
return x;
}
cout << "returning... " << x;
}
int main() {
cout << "\nmain() = " << getNum() << endl;
return 0;
}