Forums Register Login

If construct?

+Pie Number of slices to send: Send
The output of the foll code is
Ans : It'll print numbers from 0 to 4
The code is as follows :

Can any one explain me how did they get this output and why?
(need Proper Explainations)
Sonir
[Code edited by Val. PLEASE USE THE CODE tags]
[This message has been edited by Valentin Crettaz (edited December 10, 2001).]
+Pie Number of slices to send: Send
void crazyLoop() {int c = 0;JACK: while (c < 8) {JILL: System.out.println(c);if (c > 3) break JACK; else c++;}}
Sonir
Here is what I think is happening:
Your first loop is Jack, which runs from c=0 to c=7. Your second loop is Jill, which stops Jack when c > 3 (the first time that happens is when c = 4). Since the print statement happens before the break statement, all values of c will be printed out, including the first value that will make the test in Jill false. Then we break out of Jack, and move on.
Pete
+Pie Number of slices to send: Send
Hi Peter & Sonir,
Actually there is only one loop. The second 'loop' is just a print statement within the Jack loop. Note that in this case you would get the same behavior without the labels:
int c=0;
while (c < 8) {<br /> System.out.println(c);<br /> if (c > 3)
break;
else
c++;
}
So like Peter said, c will never be greater than 4. As soon as it is, the if statement is true and the loop is broken. No further increments or iterations are completed.
Also note that the 'Jill' label is useless.
Hope that is helpful,
--Kelley

Originally posted by Peter Chirco:
Here is what I think is happening:
Your first loop is Jack, which runs from c=0 to c=7. Your second loop is Jill, which stops Jack when c > 3 (the first time that happens is when c = 4). Since the print statement happens before the break statement, all values of c will be printed out, including the first value that will make the test in Jill false. Then we break out of Jack, and move on.
Pete[/B]


Where does a nanny get ground to air missles? Protect this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 769 times.
Similar Threads
Expression in for loop
Labels
How to split string but keep all delimiters
NX: Bext free style checker ?
label
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:28:21.