i= 1
while (i<=3):
print("i",i)
j=1
while (j<3):
print("j",j)
j=j+1
i=i+1
print("Done!")
Now I am wondering? Why would the output not be: i1 j1 j2 i2 i3
and instead it is: i1 j1 j2 i2 j1 j2 i3 j1 j2
Why does the rightmost while loop keep repeating even though the value of j is already satisfied eventually by it.
-
3You see that you are re-initializing j to 1 in outer loop?Rohit Jain– Rohit Jain2012年10月25日 16:24:05 +00:00Commented Oct 25, 2012 at 16:24
-
In line 4, you reset the value of j to 1 on each iteration of i.JerseyMike– JerseyMike2012年10月25日 16:25:39 +00:00Commented Oct 25, 2012 at 16:25
2 Answers 2
That's because. you are re-initializing your j to 1 in the outer while loop. So, every time your outer loop, starts, your inner loop will run two times.
while (i<=3):
print("i",i)
j=1 <-- This re-initializes the value of `j`
while (j<3):
print("j",j)
j=j+1
i=i+1
1 Comment
This is best explained by use of a trace table
1) all the variables and conditions are layed out along the top
2) each time a variable/condition changes you go one row down and enter into the table
enter image description here
Line 1: i is initialized to 1
Line2: condition i <=3 is True so add to trace table one row down
Line 3: j is initialized to 1
Line 4-8 the inner while loop runs until j<3 becomes false
What is happening is the out while loop is running once where upon it meets another indented while loop which must run its course before i is next incremented.
One side effect or interesting point of algorithm complexity is that the inner while loop will run its course the number of times the outer while loop runs. This is in order of N * N. You can see this is true from the truth table.The inner while runs three times (not actually n times but N-1) as j stops before it gets to the third iteration.