Chapter 9 Control Structures
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.
while loop While Syntax: Flowchart: while (boolean condition) { repeated statements }
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
do while loop Do While Syntax: Flowchart: do { repeated statements } while (boolean condition);
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);
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.
for loop logic
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
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
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
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 ); }
Break Statement for (int index =1; index<= 1000; index ++) { if (index == 400) { break; } System.out.println("The index is " + index); }
Continue Statement for (int index = 1, index <= 1000; index ++) { if (index == 400) { continue; } System.out.println("The index is " + index); }