Loops –Do while Do While Reading for this Lecture, L&L, 5.7
The do Statement A do statement has the following syntax: The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false do { statement; } while ( condition );
The do Statement An example of a do loop: The body of a do loop executes one or more times (Note: at least once) See ReverseNumber.java (page 244)ReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5);
The do-while Statement public class DoWhileDemo { //Execution always starts from main public static void main(String[] args) { System.out.println(“Enter a number:”); Scanner keyboard = new Scanner(System.in) int num = keyboard.nextInt(); int count = 0; do { count++; System.out.println(count); } while(count <= num); } do Loop_Body while(Boolean_Expression); The loop body may be either a single statement or more likely a compound statement
The do-while Statement true Start Execute Loop_Body do Loop_Body while(Boolean_Expression); false End loop Evaluate Boolean_Expression
The do-while Statement true false Start End loop do { System.out.print(count+ “,”); count++; } while(count <= num); Execute { System.out.print(count+ “,”); count++; } Evaluate count <= num
Difference between while and do-while Statements Do while -Do while statement is executed at least once -Condition is checked after executing statements in loop body While -While statement may be executed zero or more times -Condition is checked before executing statements in loop body
Break in Loops The break statement causes execution to “break” out of the repetitive loop execution (goes just outside the loop’s closing “}”) The effect of break statement on a loop is similar to effect on switch statement. The execution of the loop is stopped and the statement following the loop is executed.
Break in Loops int count = 1; while(count != 50) { count += 2; if(count % 2 == 1) break; }