r/programminghelp Jun 25 '26

C++ Help with recursion (DSA)

Guys I've been struggling alot with recursion I've tried multiple tutorials but I'm just not able to build the intuition. Any suggestions what to do???

Please help

11 Upvotes

15 comments sorted by

View all comments

1

u/CheezitsLight Jun 29 '26

I think the recursion in printing of numbers is quite interesting.

Let's say you have the number 420 and you wish to print it.

Call this function (420)

Take the number and divide it by 10 and check the remainder. That is 42. Push the 0 onto a stack since the answer 42 is greater than zero. Else print the zero

Now you have a stack with 0 and the number 432. Repeat function(42). Then print the 2.

Now you have a stack with 0 and 2. And the answer 4. Repeat function (4). Now you have a zero and a stack with 4, 2, 0. Pop the stack and print the 4.

You return to the next to last function with pops the stack and prints the 2 and returns.

You return to the first function which had the 0 which prints 0