Reputation: 315
I have the following code example and I cannot figure out why it displays 123. Since these are integers I understand the decimals are not displayed. But I expected it to show 3, 2(.3), 1(.23) (in the opposite order). When n goes below 10 everything stops after the final cout... right?
#include <iostream>
using namespace std;
void recursion(int n) {
if (n < 10) cout << n;
else {
recursion(n / 10);
cout << n % 10;
}
}
int main() {
recursion(123);
return 0;
}
Upvotes: 1
Views: 526
Reputation: 73627
Well, you call with 123 as n
, the function executes the statement:
if (n < 10) // its false, so it continues with else:
else {
recursion ( n /10 ) // recursive call n/10 = 123/10 = 12 (as it's int)
...
It will continue like this, recursively calling with n
being 12
recursion (n/10) // second recursion call n=12, so n/10 = 1
then the function is executed, with n being 1 so smaller than 10
if (n < 10) // its true
cout << n; // 1 gets printed
else // no, the rest is skiped
...
then it returns from recursion. So we're back in the context where n
was 12. The next statement to be executed in that context is :
cout << n %10; // prints 12 % 10, which is 2
then, continuing like this, similarly it will print 123%10, which is 3. In conclusion, the 123 that is printed has nothing to do with the 123 entered as input.
I think you wanted to do :
...
else {
cout << n % 10; // first print to see the count down
recursion(n / 10); // then recurse
}
But you have to learn using a debugger. As long as you don't, put some extra cout
to visualize what's happening.
Upvotes: 5