0
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.

asked Oct 25, 2012 at 16:22
2
  • 3
    You see that you are re-initializing j to 1 in outer loop? Commented Oct 25, 2012 at 16:24
  • In line 4, you reset the value of j to 1 on each iteration of i. Commented Oct 25, 2012 at 16:25

2 Answers 2

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
answered Oct 25, 2012 at 16:24
Sign up to request clarification or add additional context in comments.

1 Comment

@user1716168. Yeah. you can do it after that. Generally, it is assumed that it takes at least 10 - 15 minutes to solve a problem. that is why that time.
0

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.

answered Oct 25, 2012 at 20:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.