Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Loop variations do-while and for loops

2 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

3 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

4 do { sum += number; number++; } while ( sum <= 1000000 ); Syntax for the do-while Statement do while ( ) ; Statement (loop body) Boolean Expression

5 Control Flow of do-while int sum = 0, number = 1 sum += number; number++; sum += number; number++; sum <= 1000000 ? true false

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

7 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 100) { System.out.println(“Value out of range”); System.out.print(“Enter a number between 1 and 100: ”); x = kb.nextInt(); }

8 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 100) System.out.println(“Value out of range”); } while(x 100);

9 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.

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

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

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

13 For loops Count-controlled loops are so common in programming that most languages have a special set of syntax designed specifically for this construct for loopIn Java, the special syntax for a count- controlled loop is called a for loop

14 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

15 For Loop Syntax for ( initialization ; test expression ; update ) { 0 or more statements to repeat }

16 Control Flow of for i = 0; false number =... ; sum += number; true i ++; i < 20 ?

17 The for loop contains an initialization an expression to test for continuing an update to execute after each iteration of the body

18 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 */ }

19 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 the while loop version

20 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

21 for (int count = 4 ; count > 0 ; count -- ) { System.out.println(“” + count); } System.out.println(“Done”); Example using decrement OUTPUT: 4 3 2 1 Done

22 Write a loop to produce the following output: 1Potato 2Potato 3Potato 4 5Potato 6Potato 7Potato More

23 What is output? int count=0; for (; count < 10 ; count++ ) { System.out.println(“  ”); }

24 What is output? int count=0; for (; count < 10 ; count++ ); { System.out.println(“*”); }

25 More for Loop Examples for (int i = 0; i < 100; i += 5) 1 1 i = 0, 5, 10, …, 95 for (int j = 2; j < 40; j *= 2) 2 2 j = 2, 4, 8, 16, 32 for (int k = 100; k > 0; k--) ) 3 3 k = 100, 99, 98, 97,..., 1

26 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

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

28 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.

29 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."); }

30 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.


Download ppt "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."

Similar presentations


Ads by Google