algorithm - Nested loop execution -


this simple question, reason i'm getting confused , it's annoying.

def test(): lo1 hi1:     j lo2 hi2:     body() 

how many times body() execute for: lo1=1, hi1=n, lo2=i-2, hi2=i+2

the answer 5n times, have no idea how it!

i think easiest way understand run it.

for example n=10, following java code prints values of i , j in each iteration :

 (int i=0; i<=10; i++){      (int j=i-2; j<=i+2; j++)          system.out.println("i = " + + ", j= " + j);  } 

the result follows:

i = 0, j= -2 = 0, j= -1 = 0, j= 0 = 0, j= 1 = 0, j= 2 = 1, j= -1 = 1, j= 0 = 1, j= 1 = 1, j= 2 = 1, j= 3 = 2, j= 0 = 2, j= 1 = 2, j= 2 = 2, j= 3 = 2, j= 4 = 3, j= 1 = 3, j= 2 = 3, j= 3 = 3, j= 4 = 3, j= 5 = 4, j= 2 = 4, j= 3 = 4, j= 4 = 4, j= 5 = 4, j= 6 = 5, j= 3 = 5, j= 4 = 5, j= 5 = 5, j= 6 = 5, j= 7 = 6, j= 4 = 6, j= 5 = 6, j= 6 = 6, j= 7 = 6, j= 8 = 7, j= 5 = 7, j= 6 = 7, j= 7 = 7, j= 8 = 7, j= 9 = 8, j= 6 = 8, j= 7 = 8, j= 8 = 8, j= 9 = 8, j= 10 = 9, j= 7 = 9, j= 8 = 9, j= 9 = 9, j= 10 = 9, j= 11 = 10, j= 8 = 10, j= 9 = 10, j= 10 = 10, j= 11 = 10, j= 12 

you can see there 10 iterations i, , each i have 5 iterations of j(from i-2 i+2). hence 50 (5*n) iterations in total.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -