Gawkzz Gawkzz - 1 year ago 65
C++ Question

Need help understanding recursion

So in my

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
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?

Answer Source

Testing by random number (13)

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!

For future

You should use a pencil and a paper , and debug your self manually just like we did above. OR even better use a debugger like GDB! How to debug via GDB? This is an excellent quick startup!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download