Download presentation
Presentation is loading. Please wait.
Published byGarrett Vallance Modified over 10 years ago
1
Loops –Do while Do While Reading for this Lecture, L&L, 5.7
2
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 );
3
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);
4
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
5
The do-while Statement true Start Execute Loop_Body do Loop_Body while(Boolean_Expression); false End loop Evaluate Boolean_Expression
6
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
7
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
8
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.
9
Break in Loops int count = 1; while(count != 50) { count += 2; if(count % 2 == 1) break; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.