For Loops
For Loops
DSI
Review
• General Form of a switch statement:
switch (SwitchExpression) {
case CaseExpression1:
//One or more statements
break;
case CaseExpression2:
//One or more statements
break;
default:
//One or more statements
}
• CaseExpressions must be of type…
•
char, byte, short, or int.
Review
• A loop is…
• a control structure that causes a statement or group of statements to
repeat.
• Two looping structures talked about so far…
• while Loop
• do-while Loop
False
The for Loop
for(int count = 0; count < 5; count++)
System.out.println("Hello!");
• This will print “Hello!” 5 times.
• First, count is initialized to 0.
• count is often called a counter variable because it keeps count of the number of
iterations.
• Then, count < 5 is tested.
• It is true so the body is executed.
• Then, count is incremented.
• This happens 5 times until count = 5 which makes count < 5 false.
• Note that count is declared inside of the loop header, this makes it have
block-level scope in the loop.
• This implies that it can be used in the body of the loop.
• The counter variable can be declared outside of the header.
The for Loop Notes
• Remember: the for loop is a pretest loop.
• Use the update expression to modify the control variable, not a statement in
the body of the loop (unless there is no way to avoid it)
• You can use any statement as the update expression:
• count--
• count += 2
• You can declare the loop control variable outside of the loop header, and it’s
scope will not be limited to the loop.
int count;
for(count= 0; count < 5; count++)
System.out.println("Hello!");
count = 99;
User-Controlled for Loop
• Sometimes, you may want the user to determine how many times
the loop should iterate.
• Example: UserControlledForLoop.java
• https://repl.it/@DSIcogc/UserControlledForLoop#Main.java
break and continue
• Java provides two keywords that can be used to modify the normal
iteration of a loop:
• break – when encountered in a loop, the loop stops and the program
execution jumps to the statement immediately following the loop.
• continue – when encountered in a loop, the current iteration of the
loop stops immediately.
• Example: BreakAndContinue.java