aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "for loop" Watch "for loop" New topic
Author

for loop

Wesley Liu
Greenhorn

Joined: Dec 12, 2000
Posts: 7
maybe this is a silly question, but I really need help
here is the code
public class test{
public static void main(String args[]){
oor: for (int i=0;i<10;i++){
for (int j=0;j<10;j++){
if(i+j>10){break oor;}
System.out.print(i+""+j+" ");
}
}
}
}
the output is when i=0, j=0 to 9;
when i=1,j=0 to 9;
when i=2,j=o to 8;
then, it just stoped, nothing else printout. can anybody tell me why there is no such a situation when i=3,j=0 to 7? or the rest?
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
hi .. have a look at the following code
<br /> when u run this code you will see that after the last value 28 the line "Terminated both loops" gets printed and the program quits.<br /> <br /> what is happening here is that the labelled break that you have used is executed when the condition i+j>10 is met ... but this condition is met for the first time when the value of i=2 and j=9 ... so at this point the control shifts outside the for loops since you have used a labelled break outside the two loops
hope that helps
Samith.P.Nambiar
<pre>
\```/
(o o) harder u try luckier u get
-------oOO--(_)--OOo----------------------------
</pre>
lusha tak
Ranch Hand

Joined: Dec 30, 2000
Posts: 185
this is because as soon as the condition for the break clause becomes true ( i.e. i+j>10)it comes out of the both the loops
Hope that helps
Lusha
Prasanna Wamanacharya
Ranch Hand

Joined: Apr 24, 2001
Posts: 143
Hi Wesley, the reason for the output is the "break" statement. When i=2, j=8, i+j=10, and this is the last thing which is printed out. After this iteration, i=2, j=9, i+j>10, and the break statement is executed. Note where the label of the break statement is located; it is located at the beginning of the outer loop. Hence, the outer loop is terminated, and nothing else is printed out.
If instead of the break statement, a continue statement is used, then the outer loop is not terminated, but the iterations where the value of i+j>10 are just skipped, and all other values of i&j are printed out.
HTH
Prasanna
SCJP2
dipak chand
Greenhorn

Joined: May 28, 2001
Posts: 5
when u run this code you will see that after the last value 28 the line "Terminated both loops" gets printed and the program quits.
what is happening here is that the labelled break that you have used is executed when the condition i+j>10 is met but this condition is met for the first time when the value of i=2 and j=9 . It comes more than 10. Due to this it doesnt go futher
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for loop