loop variations do-while and for loops. do-while loops slight variation of while loops instead of...

30
Loop variations do-while and for loops

Post on 20-Dec-2015

249 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Loop variations

do-while and for loops

Page 2: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Do-while loops

• Slight variation of while loops• Instead of testing condition, then

performing loop body, the loop body is performed first, then condition is tested

• A do-while loop is guaranteed to perform one iteration, because the validity of the condition is not known until after the iteration is complete

Page 3: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Syntax for do-while loop

do {/* loop body statements */

}while (expression);

Notes:• do-while loops are almost always event-controlled• Often not necessary to initialize loop control• Good idea to keep end bracket and while(expression) on same line

Page 4: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

do {

sum += number;

number++;

} while ( sum <= 1000000 );

Syntax for the do-while Statementdo

<statement>

while ( <boolean expression> ) ;

Statement(loop body)

Statement(loop body)

Boolean ExpressionBoolean Expression

Page 5: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Control Flow of do-while

int sum = 0, number = 1int sum = 0, number = 1

sum += number;

number++;

sum += number;

number++;

sum <= 1000000 ?

sum <= 1000000 ?

true

false

Page 6: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Applications for do-while loops

• Often used to display an initial menu of choices, one of which is “quit program” – you want user to see this at least once, even if the option they pick is to quit

• Useful for checking validity of input value – eliminates having to prompt twice for same data (see examples, next two slides)

Page 7: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Validating input – while loop

Scanner kb = new Scanner(System.in);int x;System.out.print(“Enter a number between 1 and 100: ”);x = kb.nextInt();while(x < 1 || x > 100) {

System.out.println(“Value out of range”);System.out.print(“Enter a number between 1 and 100: ”);x = kb.nextInt();

}

Page 8: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Validating input – do-while loop

Scanner kb = new Scanner(System.in);int x;

do {System.out.print(“Enter a number between 1 and 100: ”);x = kb.nextInt();if (x < 1 || x > 100)

System.out.println(“Value out of range”);} while(x < 1 || x > 100);

Page 9: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Do-While Loop vs. While Loop

• POST-TEST loop (exit-condition)

• The looping condition is tested after executing the loop body.

• Loop body is always executed at least once.

• PRE-TEST loop (entry-condition)

• The looping condition is tested before executing the loop body.

• Loop body may not be executed at all.

Page 10: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Confirmation Dialog• A confirmation dialog can be used to prompt the user

to determine whether to continue a repetition or not.

JOptionPane.showConfirmDialog(null,

/*prompt*/ "Play Another Game?",

/*dialog title*/ "Confirmation",

/*button options*/ JOptionPane.YES_NO_OPTION);

Page 11: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Example: Confirmation Dialog

boolean keepPlaying = true;

int selection;

while (keepPlaying) {

//code to play one game comes here

// . . .

selection = JOptionPane.showConfirmDialog(null,

"Play Another Game?",

"Confirmation",

JOptionPane.YES_NO_OPTION);

keepPlaying = (selection == JOptionPane.YES_OPTION);

}

Page 12: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Example: Confirmation Dialog

int selection;

do {

//code to play one game comes here

// . . .

selection = JOptionPane.showConfirmDialog(null,

"Play Another Game?",

"Confirmation",

JOptionPane.YES_NO_OPTION);

} while (selection == JOptionPane.YES_OPTION);

Page 13: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

For loops

• Count-controlled loops are so common in programming that most languages have a special set of syntax designed specifically for this construct

• In Java, the special syntax for a count-controlled loop is called a for loopfor loop

Page 14: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Count-controlled loops

• Count-controlled while loop:– initialize counter before loop starts– test counter in loop control expression– update counter inside loop body

• A for loop is a stylized version of a count-controlled while loop; all of the elements above appear at the top of the loop

Page 15: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

For Loop Syntax

for ( initialization ; test expression ; update ) {

0 or more statements to repeat

}

Page 16: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Control Flow of for

i = 0;i = 0;

false

number = . . . ;sum += number;

number = . . . ;sum += number;

true

i ++;i ++;

i < 20 ? i < 20 ?

Page 17: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

The for loop contains

an initialization

an expression to test for continuing

an update to execute after each iteration of the body

Page 18: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Count-controlled while loop example

int x=0; /* step 1: initialize counter */

while (x < 100) /* step 2: test counter value */{

System.out.println(“I will be a good student”);x++; /* step 3: increment counter */

}

Page 19: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Same logic using for loop

for (int x=0; x<100; x++) System.out.println(“I will be a good student”);

Step 1: initialize loop counter (performed once)

Step 2: test counter value (performed once for each iteration)

Step 3: increment loop counter (performed once per iteration)

Body of loop is performed between steps 2 and 3, just as in thewhile loop version

Page 20: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Notes on for loop

• Just stylized version of while loop; condition test occurs before each iteration

• Can contain single statement (making brackets unnecessary) because increment occurs in loop heading

• Each section of loop heading can contain multiple parts, separated by commas; each section can also be omitted

Page 21: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

for (int count = 4 ; count > 0 ; count-- )

{

System.out.println(“” + count);

}

System.out.println(“Done”);

Example using decrement

OUTPUT: 4321Done

Page 22: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Write a loop to producethe following output:

1Potato2Potato3Potato45Potato6Potato7PotatoMore

Page 23: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

What is output?

int count=0;

for (; count < 10 ; count++ )

{

System.out.println(“”);

}

Page 24: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

What is output?

int count=0;

for (; count < 10 ; count++ );

{

System.out.println(“*”);

}

Page 25: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

More for Loop Examplesfor (int i = 0; i < 100; i += 5)11

i = 0, 5, 10, … , 95 i = 0, 5, 10, … , 95

for (int j = 2; j < 40; j *= 2)22

j = 2, 4, 8, 16, 32 j = 2, 4, 8, 16, 32

for (int k = 100; k > 0; k--) )33

k = 100, 99, 98, 97, ..., 1k = 100, 99, 98, 97, ..., 1

Page 26: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Example – multiplication table

The loop displays a specified multiplication table. For example, if the user enters 6, the program displays this table:

1 x 6 = 6 2 x 6 = 12 3 x 6 = 18

.

.

.

12 x 6 = 72

Page 27: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

import java.util.*;

public class Mtable {public static void main(String [] args) {int value;Scanner kb = new Scanner(System.in);System.out.print (“Enter value for table: ”);value = kb.nextInt();for (int ct = 1; ct <= 12; ct++)

System.out.println( “” + ct + “ x ” + value+ “ = ” + ct * value);

}}

Page 28: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Loop-and-a-Half Repetition Control

• Loop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body.

• It is implemented by using reserved words while, if, and break.

Page 29: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Example: Loop-and-a-Half Control

String name;

while (true) {

name = JOptionPane.showInputDialog(null, "Your name");

if (name.length() > 0)

break;

JOptionPane.showMessageDialog(null, "Invalid Entry.\n" +

"You must enter at least one character.");

}

Page 30: Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop

Pitfalls for Loop-and-a-Half Control

• Be aware of two concerns when using the loop-and-a-half control:– The danger of an infinite loop. The boolean

expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop.

– Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control flow.