I need to write a recursive function reverseInput that until the user enters zero it keeps on accepting numbers, then when done, outputs them in reverse order. Only thing, i cannot use strings or arrays or anything of the like and it must be done in one recursive function. It should work like this:
enter a number:2
enter a number:53
enter a number:0
the numbers you have entered in reverse:53,2
I'm stumped again

9 Years
Discussion Span
Last Post by Ancient Dragon

That's not hard to do, but you have to be very careful of getting stack overflow errors. And that's pretty each to do with recursive functions.

>>I'm stumped again
Do you know what a recursive function is? If not then read about them in your text book. Its simply a function that calls itself.

int foo()
   foo(); // recursion

Don't compile or run the above because it will kill your os.


How will the program know the number orders if I can't use an array?
I know what a recursive function is; is it really simple and I'm just thinking too hard?

void foo()
   // ask for input
   // if input != 0 do recursion
   // print the number entered in this instance of the function and print a comma after it

It works but I don't really understand why. If the number isn't zero you call the function again and then output the number, how does this result in the numbers reversed?


after you enter 0 then the recursion unwinds and only the line that prints the value is executed. That is done in the reverse order that they were called.

>>If the number isn't zero you call the function again and then output the number
No it doesn't work quite that way. The printing doesn't start until after returns from the recursion.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.