Nested while loop | Sololearn: Learn to code for FREE!

0

Nested while loop

m = 0 x = 1 while x < 4: y = 1 while y < 3: m = m + x + y y = y + 1 x = x + 1 print(m) My solution as follows: m=0 x=1 y=1 1<3 m=0+1+1 m=2 y=y+1 y=2 x=1+1 x=2 m=2 x=2 y=2 2<3 m=0+2+2 m=4 y=2+1 y=3 x=2+1 x=3 m=4 x=2 y=3 2<4 m=4+2+3 m=9 y=3+1 y=4 x=2+1 x=3 m=9+3+4 m=16 The output is 21. I got output 16?

1/22/2022 9:24:12 PM

Knowledge Is Power

5 Answers

New Answer

+1

You missed the fact that y = 1 every time you start an iteration in the first while. So in every iteration of the first while y gets the same value 1. You can define y outside while so that it gets higher value every iteration.

0

The inner loop satisfied when x=3. After it moves to outer loop where value for x=3, y=1 and m’s value changed as well? Sorry trying to understand the syntax. Please help!

0

Here some notes on your solution, you can see where exactly there is a problem. I hope it will help. m=0 x=1 y=1 1<3 m=0+1+1 m=2 y=y+1 y=2 #here you shouldn't go outside while until the condition y<3 becomes false. (x=1+1)#You shouldn't do that yet, you still in second while that means x still 1 and you go to the next iteration of the second while. x=2 #x=1 m=2 x=2 y=2 2<3 m=0+2+2 # here m has the value 2 so you should keep it and do m=2+x+y = 2+1+2 (don't forget x is 1 not 2) m=4 #m=5 y=2+1 y=3 x=2+1#same thing you don't get that until you exit the second while x=3 m=4 x=2 y=3# if y ==3 you don't execute any iteration of the second while cause 3<3 is a false statement. After that all operations in the second while are ignored. 2<4 m=4+2+3 #not done cause you already exited the second while m=9 y=3+1 y=4 #same thing 4 is greater than 3 so you ignore the operations you did with false condition x=2+1 x=3 m=9+3+4 m=16 So you'll exit the first while when y==2 and the first while when x==3.Finally you print m.

0

Finally found my mistake! Thank you so much for your help👍

0

You are welcome ! Good luck 👍