loops copyright © 2012 pearson education, inc.. conditionals and loops (chapter 5) so far, we’ve...

26
Loops Copyright © 2012 Pearson Education, Inc.

Upload: vanessa-ford

Post on 18-Jan-2018

220 views

Category:

Documents


0 download

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

Page 1: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

Loops

Copyright © 2012 Pearson Education, Inc.

Page 2: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 3: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 4: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 5: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

Logic of a while Loop

statement

truefalse

conditionevaluated

Copyright © 2012 Pearson Education, Inc.

Page 6: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 7: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

The General While Statement (with an index)

initialization;while ( condition ){ statement; increment;}

Copyright © 2012 Pearson Education, Inc.

Page 8: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 9: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

Copyright © 2012 Pearson Education, Inc.

Page 10: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 11: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 12: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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);

}

Page 13: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

Do this:

for(int num = -10; num <= 10; num += 2)

{

System.out.println(num);

}

// Print even number between -10 and 10 inclusive

Page 14: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 15: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 16: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 17: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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)); } }}

Page 18: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 19: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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!!!

Page 20: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 21: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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++;}

Page 22: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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

Page 23: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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}

Page 24: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 25: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

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.

Page 26: Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare

Homework• CodingBat exercises• Work on Project

Copyright © 2012 Pearson Education, Inc.