Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested loop and break  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



In the above program,execution start at i=1 and check the condition 1<5 true
J=1 1<5 true
Print I=1 j=1
J==2 condn false
Next i thought next j++ operation would perform that means j=2 2<5(j loop) true
Print i=1 j=2
j==2 condn true so break(come out of the j loop)
Print i=1(i loop)
i++(i=2)2<5 true
J=1 and so on

But when I run this program i=1 j=1(j loop)
i=1(i loop)
i1j2(j loop)
i2j1(j loop)
i2(i loop) and so on.I couldn�t get it.Please someone help me.
 
Madhura Prakash
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I think its not working coz, the index variable "i" is not declared in the first for loop. Guess u have missed declaring the variable "i".

Regards,
Madhura.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply Madura.But i declared it previously in my whole program
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This line

System.out.println("i"+i);

is inside the "j" loop; your explanation suggests you believe it's inside the "i" loop but after the "j" loop.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you fix the declaration of i (i assume you did that outside of this code segment), here's what happens...

we print the i=1j=1. then, the j==2 test fails, so we don't break. so, we print i=1, since that print statement is still inside the j-loop.

we then increment j to 2. we pass the j-loop test, and print
i=1j=2.

NOW we pass the j == 2 test, so we break out of the j loop.

i think you believe the is outside the j-loop, but it's not. here is your code reformatted:

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much Fred and Ernest.I exactly misunderstood i=1 in i loop.Your explanations made it clear to me that i=1 in j loop(not in i loop).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!