Download presentation
Presentation is loading. Please wait.
1
Chapter 9 Repetition
2
Objectives Code programs using the following looping techniques:
While Loop Do While Loop For Loop Explain when the Break and Continue statements would be used when coding loops. Walk through While, Do While, and For loops documenting variables as they change.
3
while loop While Syntax: Flowchart:
while (boolean condition) { repeated statements }
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
5
do while loop Do While Syntax: Flowchart:
do { repeated statements } while (boolean condition);
6
do while loop example: Do While : Output:
Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 int counter = 1; do { System.out.println("Hello " + counter); counter++; } while (counter <=5);
7
for loop Initialization - initializes the start of the loop.
for (initialization; test; increment) { statements; } 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.
8
for loop logic
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
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
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); } 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
results for (int i=0, j=0 ; i*j < 1000; i++, j+=2) { System.out.println( "The answer is " + i + " * " + j + " = " + i*j ); }
13
Break Statement for (int index =1; index<= 1000; index ++) {
if (index == 400) { break; } System.out.println("The index is " + index); }
14
Continue Statement for (int index = 1, index <= 1000; index ++) {
if (index == 400) { continue; } System.out.println("The index is " + index); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.