## Understanding flow in recursion

Finding it tricky to wrap my head around recursion and would greatly appreciate some insight. I am trying to understand flow in recursion by successively diving a number by 2.

def divide_by_2(num): if num > 1: divide_by_2(num // 2) print(num) print(num % 2,num) divide_by_2(39)

output:

1 1

2

0 2

4

0 4

9

1 9

19

1 19

39

1 39

Questions I have are

1) Shouldn't 1 39 be printed first, why is it being printed right at the very end? Why is the order inverted?

2)Which of the two print statement should be executed first and why?

If we take your code (and add line numbers for clarity)

1 def divide_by_2(num): 2 if num > 1: 3 divide_by_2(num // 2) 4 print(num) 5 print(num % 2,num)

Then run through a smaller number line by line as an example

divide_by_2(4)

(call 1, num==4) Line 2 is executed, it is greater than 1 so move to line 3

(call 1, num==4) Line 3 calls the same function. It will not continue to line 4 until the function call 2 is finished executing and returns. We have not yet called a print statement so nothing shows!

(call 2, num==2) Line 2 is executed, it is greater than 1 so move to line 3

(call 2, num==2) Line 3 Recurse through the same function again will not continue executing until call 3 is finished. Still no print statement

(call 3, num==1) Line 2 is executed, it is equal to 1, move to line 5

(call 3, num==1) Line 5 We finally have a print statement! We are at the innermost call with num==1 so "1 1" is printed. Now that this function has finished, we return to line 4 in the most recent call which in this case is call 2

(call 2, num==2) Line 4 With the function returning, we start executing the next line which is print(num) which simply print "2"

(call 2, num==2) Line 5 We have another print statement, this one prints "0 2". Now that call 2 is finished executing, call 1 resumes

(call 1, num==4) Line 4 prints "4"

(call 1, num==4) Line 5 prints "0 4"

Execution ends

This gives the end result of:

1 1

2

0 2

4

0 4

The key thing to remember as to why the numbers are printed from smallest to largest is that the flow in this program prints the statements **after** recursing into the next function. This leads to the behavior call 1 -> call 2 -> call 3 -> print from call 3 -> print from call 2 -> print from call 1.

The easiest way for me to get a handle on recursion is to go through the code line by line either on paper or in my head. I hope this breakdown helps.

**Understanding flow in recursion,** If we take your code (and add line numbers for clarity) 1 def divide_by_2(num): 2 if num > 1: 3 divide_by_2(num // 2) 4 print(num) 5 print(num Let’s understand what is happening in the flow chart. In every recursive method, there is a base case which terminates the function if the condition is satisfied else the method calls itself to return the value or it may call itself successively and the chain continues unless one of the called methods meets the required condition to terminate the chain.

Take your finger and follow the lines of code (starting with the bottom line as it’s the thing that kicks everything off), every time you encounter the divide_by_2, jump back to the top

You’ll notice that you start off heading into the function with 39, and you hit another call to divide_by_2 before you print anything.

You’ll keep going like this until you get down to 1, at which point you’ll skip over the call to divide_by_2, and then you start printing things, in reverse order as the call stack unwinds

Things unwind because when you come back out of a function call, the code continues from the next line after the function call

The next line is a print statement, so the first thing to be printed is the smallest division result

It would probably greatly help your understanding to use a language that has an interactive debugger facility so you can single step the code and see it working, but if you don’t have that, think of it like multiple levels of code indenting:

divide_by_2(64) print(64) divide_by_2(64) divide_by_2(32) print(32) print(64)

Each time you recurse, you copy paste a divide/print pair into the middle blank line, in and the indent increases to demonstrate the call stack getting longer

divide_by_2(64) divide_by_2(32) divide_by_2(16) print(16) print(32) print(64) divide_by_2(64) divide_by_2(32) divide_by_2(16) divide_by_2(8) divide_by_2(4) divide_by_2(2) divide_by_2(1) print(1) print(2) print(4) print(8) print(16) print(32) print(64)

You asked which print prints first, and that one is simpler if your talking about the fact that your code contains two print statements- the one that occurs first in the source code.

If you mean why does the 39 print last, it’s because your code recourses all the way in as deep as it can go before it stops recursing, and the printing is done on the way out. If you printed before you recursed into the divide function, then the numbers would start at 39 and get smaller

**Recursion and stack,** The condition n == 1 is false, so the flow continues into the second Recursion can give a shorter code, easier to understand and support. During this phase control flow occurs as follows. F6 - > F5 - > F4 - > F3 - > F2 - > F1 - > Function which called F. Remember, all instances of F (F1,F2,..,F6) are actually F; these individual names are given simply to improve understanding of control flow. The recursion ends when the stopping condition is executed.

Start with a smaller number so you can map all the recursions at once. I'm also going to slightly re-write your function for ease of reproducibility

def divide_by_2(num): if num == 0: return # we're done divide_by_2(num//2) print(num)

Now we divide by 5...

divide_by_2(5) -> divide_by_2(2); print(5) -> divide_by_2(1); print(2); print(5) -> divide_by_2(0); print(1); print(2); print(5) -> return; print(1); print(2); print(5)

Basically: since you've put the recursive call before the rest of the function, it must complete its recursion before it can continue.

**[PDF] Translating Recursion Equations into Flow Charts,** This paper proposes the foundation for a systematic study of the translation of recursive function definitions into flow charts (often called the removal of How Recursion Works Recursion Algorithm .Tower of Hanoi in C step by AlgoData 64,521 views. 8:26. String Permutations - Understanding Recursion | Learn Algorithms with Phanto

Since 39 is > 1, it is going into the initial `if`

statement. The first line of code in that block tells it to recursively call itself with `divide_by_2(num // 2)`

(taking the integer Floor). There is no print statement hit - it just put another `divide_by_2`

on the call stack, `divide_by_2(19)`

. As such, this will continue to keep on adding to the call stack, and calling *no* print statements until `num`

is < 1.

At the top of the call stack, you get `1 1`

because that call is *not* going into the `if`

conditional, it is going immediately to `print(num % 2,num)`

.

After that, it comes back down the call stack where each function can execute (and finish) both the `print(num)`

and then `print(num % 2, num)`

, until there are no more functions to execute on the stack.

Hope that explained the 'theory' behind it a little bit.

**Recursion,** What is difference between tailed and non-tailed recursion? A recursive function is tail recursive when recursive call is the last thing executed by the function. Search less. Build more. Use Stack Overflow for Teams at work to share knowledge with your colleagues. Free 30 day trial. Start your trial.

**How recursion works (actual flow using stack memory),** In computer science, recursion is a method of solving a problem where the solution depends on Dataflow · Flow-based · Reactive · Ontology The examples in this section illustrate what is known as "structural recursion". This term refers to For basic understanding please read the following articles. Basic understanding of Recursion. Problem 1: Write a program and recurrence relation to find the Fibonacci series of n where n>2 . Mathematical Equation: n if n==0, n==1; fib(n) = fib(n-1) + fib(n-2) otherwise; Recurrence Relation: T(n) = T(n-1) + T(n-2) + O(1) Recursive program:

**Recursion (computer science),** To understand the control flow for a recursive you need to understand the basics of a stack data structure. Also, you should know that while If recursion is disabled, then the DNS server uses a process called iteration to resolve the name request. Root Hints If the DNS server does not know the address of the requested site, then it will forward the request to another DNS server.

**What is the control flow of a recursive function?,** You might have heard this joke — to understand recursion you must first and base case, and not by constructing step by step execution flow. Because the issue is the same, as is the approach for preventing recursive SharePoint update events in Flow… so, into the detail. The following flow will create a continuous loop, as the trigger action (' When an item is created or modified ') will always be invoked by the ' Update Item ' action.