Recursion - please help


#1

Suppose value of begin is 5

void printnum ( int begin )
 { 
    cout<< begin;
    if (begin< 9)
	// The base case is when begin is greater than 9      
       printnum ( begin + 1 );
    cout<< begin;
}

how the output is (5678998765)?


#2

Try executing it in your head, do what the code says.
Or, if you think the output should be something else, make an argument for that so that others can see where you’re going wrong.

It may help to start with 9 instead when doing it in your head, and then try 8


#3

when I try , the output is (567899)
how it decrease ?


#4

When a function finishes, control of the program returns to the caller

After your function calls itself, it prints the number again, it hasn’t finished after only printing it once


#5

I’m so sorry <\3
still I didn’t understant


#6

After a function finishes, the next line gets executed

stuff
function()
otherstuffhappensafterfunctioncall

The whole program doesn’t exit because a function finished. Control goes back to the caller.

Your function prints twice each time it is called.
You call your function 5 times.
Therefore, you will have 10 prints.


#7

Recursion is useful when solving a big problem can be solved by doing one step, and then solving the rest, and perhaps doing something afterwards to put the results together.

So each time you recurse, the problem is one such step smaller.

Eventually the problem is so small (trivial) that it can be solved immediately, and then the earlier calls that are waiting get the results that they need to finish, one after another, until the first call can finish and the whole thing is done.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.