Gawkzz - 1 year ago 65
C++ Question

# Need help understanding recursion

So in my

`class`
we are studying recursive functions. But I just do not understand how they work.

I'll use this code as an example.

``````// n is written to the screen vertically
// with each digit on a separate line.

void write_vertical(int n) {

if (n < 10)
{
cout << n << endl;
}
else   // n is two or more digits long
{
write_vertical(n/10);
cout << (n % 10) << endl;
}
}
``````

So if int
`n = 123;`
it will print each digit on its own line.How does this happen? how does this function work step by step?

Ok let's take 13 for example. well it's not less than 10 so it will execute the else block , and it will immediately execute the function itself with 13/10 , which in an int is 1. now 1 is less than 10 , so it will print 1 onto the screen with a new line because of `endl`. Now it will return back to the previous function call it had (before calling the function again with argument 1) and execute `13%10` . 13 modulus 10 , is 3 since its remainder becomes 3 with a new line again because of `endl`. And voila, you printed the number in a vertical line!