Chapter 5 Repetition 2 Objectives Code programs using

Chapter 5 Repetition

2 Objectives • Code programs using the following looping techniques: ▫ While Loop ▫ Do While Loop ▫ For Loop • Explain when the Break statements would be used when coding loops. • Walk through While, Do While, and For loops documenting variables as they change. Copyright © 2018 Daly & Wrigley

3 while loop While Syntax: while (boolean condition) { repeated statements } Copyright © 2018 Daly & Wrigley Flowchart:

4 while loop example: While : Output: int counter = 1; while (counter <=5) { System. out. println ("Hello " + counter); counter ++; } Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Copyright © 2018 Daly & Wrigley

5 do while loop Do While Syntax: do { repeated statements } while (boolean condition); Copyright © 2018 Daly & Wrigley Flowchart:

6 do while loop example: Do While : Output: int counter = 1; do { System. out. println("Hello " + counter); counter++; } while (counter <=5); Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Copyright © 2018 Daly & Wrigley

7 for loop for (initialization; test; statements; } increment) { Initialization - initializes the start of the loop. Example: int i = 0; Boolean Test - occurs before each pass of the loop. Example: i<10; Increment - any expression which is updated at the end of each trip through the loop. Example: i ++, j+=3 Statements are executed each time the loop is executed. Copyright © 2018 Daly & Wrigley

8 for loop logic Copyright © 2018 Daly & Wrigley

9 for loop example 1: for loop Results for (int counter =1; counter <=5; counter++ ) { System. out. println ("Hello " + counter); } Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Copyright © 2018 Daly & Wrigley

10 for loop example 2: for loop with modulus results for (int number = 0; number <1000; number++) { if ( number % 12 = = 0 ) { System. out. println("Number is " + number); } }. . . etc. Number is 996 Copyright © 2018 Daly & Wrigley

11 for loop example 3: for loop to print even numbers from 1 to 20 results for (int number = 2; number <=20; number+=2) { System. out. println("Number is " + number); } Copyright © 2018 Daly & Wrigley The number is 2 The number is 4 The number is 6 The number is 8 The number is 10 The number is 12 The number is 14 The number is 16 The number is 18 The number is 20

12 for loop example 4: for loop with multiple initialization & increments for (int i=0, j=0 ; i*j < 1000; i++, j+=2) { System. out. println( "The answer is " + i + " * " + j + " = " + i*j ); } Copyright © 2018 Daly & Wrigley results

13 Nested Loops Copyright © 2018 Daly & Wrigley

14 Break Statement for (int index =1; index<= 1000; index ++) { if (index == 400) { break; } System. out. println("The index is " + index); } Copyright © 2018 Daly & Wrigley
- Slides: 14