loops copyright © 2012 pearson education, inc.. conditionals and loops (chapter 5) so far, we’ve...
DESCRIPTION
Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions We’ll use three kinds of Java repetition statements in this class: while, for, and for -each loops Copyright © 2012 Pearson Education, Inc.TRANSCRIPT
Loops
Copyright © 2012 Pearson Education, Inc.
Conditionals and Loops (Chapter 5)• So far, we’ve looked at:
– making decisions with if– how to compare data– Boolean expressions– Working with Collections of objects (i.e., ArrayList)– repeat processing steps using a for-each loop
• Today we’ll look at:– While loops– For loops
Copyright © 2012 Pearson Education, Inc.
Repetition Statements• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by boolean expressions
• We’ll use three kinds of Java repetition statements in this class: while, for, and for-each loops
Copyright © 2012 Pearson Education, Inc.
The while Statement• A while statement has the following syntax:
while ( condition ) statement;
• If the condition is true, the statement is executed
• Then the condition is evaluated again, and if it is still true, the statement is executed again
• The statement is executed repeatedly until the condition becomes false
Copyright © 2012 Pearson Education, Inc.
Logic of a while Loop
statement
truefalse
conditionevaluated
Copyright © 2012 Pearson Education, Inc.
The while Statement• An example of a while statement:
• If the condition of a while loop is false initially, the statement is never executed
• Therefore, the body of a while loop will execute zero or more times
int count = 1;while (count <= 5){ System.out.println (count); count++;}
Copyright © 2012 Pearson Education, Inc.
Sample Run12345
The General While Statement (with an index)
initialization;while ( condition ){ statement; increment;}
Copyright © 2012 Pearson Education, Inc.
The for Statement: a condensed while• A for statement has the following syntax:
for ( initialization ; condition ; increment ) statement;
The initializationis executed once
before the loop begins
The statement isexecuted until the
condition becomes false
The increment portion is executed at the end of each
iteration
Copyright © 2012 Pearson Education, Inc.
Logic of a for loop
statement
true
conditionevaluated
false
increment
initialization
Copyright © 2012 Pearson Education, Inc.
The for Statement• An example of a for loop:
for (int count=1; count <= 5; count++) System.out.println (count);
• The initialization section can be used to declare a variable
• Like a while loop, the condition of a for loop is tested prior to executing the loop body
• Therefore, the body of a for loop will execute zero or more times
Copyright © 2012 Pearson Education, Inc.
Sample Run12345
The for Statement• The increment section can perform any calculation:
for (int num=100; num > 0; num -= 5) System.out.println (num);
• A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance (i.e., with an index)
• See Multiples.java (p. 281)
• See Stars.java (p. 283)
Copyright © 2012 Pearson Education, Inc.
Sample Run10095908580...15105
What does this do?
// Print multiples of 3 that are below 40.
for(int num = 3; num < 40; num = num + 3) {
System.out.println(num);
}
Do this:
for(int num = -10; num <= 10; num += 2)
{
System.out.println(num);
}
// Print even number between -10 and 10 inclusive
Sentinel Values (while)• Let's look at some examples of loop processing
• A loop can be used to maintain a running sum
• A sentinel value is a special input value that represents the end of input
• See Average.java
Copyright © 2012 Pearson Education, Inc.
Copyright © 2012 Pearson Education, Inc.
//********************************************************************// Average.java Author: Lewis/Loftus//// Demonstrates the use of a while loop, a sentinel value, and a// running sum.//********************************************************************
import java.text.DecimalFormat;import java.util.Scanner;
public class Average{ //----------------------------------------------------------------- // Computes the average of a set of values entered by the user. // The running sum is printed as the numbers are entered. //----------------------------------------------------------------- public static void main (String[] args) { int sum = 0, value, count = 0; double average;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt();
continue
Copyright © 2012 Pearson Education, Inc.
continue
while (value != 0) // sentinel value of 0 to terminate loop { count++;
sum += value; System.out.println ("The sum so far is " + sum);
System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); }
continue
Copyright © 2012 Pearson Education, Inc.
continue
System.out.println ();
if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } }}
Copyright © 2012 Pearson Education, Inc.
continue
System.out.println ();
if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } }}
Sample RunEnter an integer (0 to quit): 25The sum so far is 25Enter an integer (0 to quit): 164The sum so far is 189Enter an integer (0 to quit): -14The sum so far is 175Enter an integer (0 to quit): 84The sum so far is 259Enter an integer (0 to quit): 12The sum so far is 271Enter an integer (0 to quit): -35The sum so far is 236Enter an integer (0 to quit): 0
The average is 39.333
Infinite Loops• The body of a while loop eventually must make the condition
false
• If not, it is called an infinite loop, which will execute until the user interrupts the program
• An example of an infinite loop:
• This loop will continue executing until interrupted (Control-C) or until an underflow error occurs
int count = 1;while (count <= 25){ System.out.println (count); count = count - 1;}
Copyright © 2012 Pearson Education, Inc.
Sample Run10-1-2-3-4-5-6...Never ends!!!
Nested Loops• Similar to nested if statements, loops can be
nested as well
• That is, the body of a loop can contain another loop (or if statements, etc.)
• For each iteration of the outer loop, the inner loop iterates completely
• See PalindromeTester.java
Copyright © 2012 Pearson Education, Inc.
Quick Check
Copyright © 2012 Pearson Education, Inc.
How many times will the string "Here" be printed?
count1 = 1;while (count1 <= 10){ count2 = 1; while (count2 < 20) { System.out.println ("Here"); count2++; } count1++;}
Quick Check
Copyright © 2012 Pearson Education, Inc.
How many times will the string "Here" be printed?
count1 = 1;while (count1 <= 10){ count2 = 1; while (count2 < 20) { System.out.println ("Here"); count2++; } count1++;}
10 * 19 = 190
Review: Loop Templates
Copyright © 2012 Pearson Education, Inc.
While Loop Index Template:
initialize indexwhile (condition){ statements to be repeated update index}
For Loop Template:
for (initialize index; condition; update index){ statements to be repeated}
For Each Loop Template:
for (ElementType elementName : collection){ statements to be repeated}
While Loop Sentinel Template:
get input valuewhile (input != end condition){ statements to be repeated get input value}
Practice! Test in main• Write a for loop that prints out the numbers 1 to 26
on a single line, separated by spaces:
1 2 3 4 5 6 7 8 9 10 … 20 21 22 23 24 25 26
• Write a for loop that prints out the letters A to Z on a single line, separated by spaces:
A B C D E F G H I J … T U V W X Y Z
Hint: maybe your loop variable should be a char rather than an int
Copyright © 2012 Pearson Education, Inc.
Practice! continued• Write a for loop that prints out all the multiples of 5,
from 0 to 100 (inclusive).
• Write a while loop that prints out all the multiples of 3, from 0 to 21 (inclusive).
• Write a while loop that prints out random numbers from 1 to 10 (inclusive) until the number 0 is generated.
Copyright © 2012 Pearson Education, Inc.
Homework• CodingBat exercises• Work on Project
Copyright © 2012 Pearson Education, Inc.