Title: Loops
1Loops Do while
- Do While
- Reading for this Lecture, LL, 5.7
2The 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 )
3The 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)
int count 0 do count
System.out.println (count) while (count lt 5)
4The 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 lt num)
-
do Loop_Body while(Boolean_Expression)
The loop body may be either a single statement or
more likely a compound statement
5The do-while Statement
Start
do Loop_Body while(Boolean_Expression)
Execute Loop_Body
true
Evaluate Boolean_Expression
false
End loop
6The do-while Statement
do System.out.print(count ,)
count while(count lt num)
Start
Execute System.out.print(count ,)
count
Evaluate count lt num
true
false
End loop
7Difference 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
8Break in Loops
- The break statement causes execution to break
out of the repetitive loop execution (goes just
outside the loops 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.
9Break in Loops
int count 1 while(count ! 50) count
2 if(count 2 1) break