15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Looping Statements 551<br />

Because no break command is right above the case 21: statement, the<br />

Java program falls-through to the next CASE statement. In C#, you must<br />

explicitly define the fall-through (if this is what you want), such as<br />

Book VI<br />

Chapter 2<br />

switch (age) {<br />

case 17:<br />

case 18:<br />

case 19;<br />

case 20;<br />

System.out.println(“You’re too young to drink.”);<br />

goto case 21;<br />

case 21:<br />

System.out.println(“You’re old enough to drink.”);<br />

}<br />

Java and C#<br />

This C# SWITCH statement explicitly tells the computer to fall-through to the<br />

case 21: statement. If you omit the goto case 21 statement, the preceding<br />

C# SWITCH statement won’t work. By <strong>for</strong>cing you to explicitly define the<br />

fall-through in a SWITCH statement, C# helps prevent mistakes in writing a<br />

SWITCH statement incorrectly.<br />

Looping Statements<br />

A looping statement repeats one or more commands <strong>for</strong> a fixed number of<br />

times or until a certain Boolean condition becomes True. To create a loop<br />

that repeats <strong>for</strong> a fixed number of times, use the FOR loop, which looks like<br />

this:<br />

<strong>for</strong> (startvalue; endvalue; increment) {<br />

Command;<br />

}<br />

If you wanted the FOR loop to run five times, you could set the Start value to<br />

1 and the End value to 5, such as<br />

<strong>for</strong> (i = 1; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!