Loops - PowerPoint PPT Presentation

About This Presentation
Title:

Loops

Description:

public class DoWhileDemo //Execution always starts from main ... The execution of the loop is stopped and the statement following the loop is executed. ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 10
Provided by: Anu7
Category:

less

Transcript and Presenter's Notes

Title: Loops


1
Loops Do while
  • Do While
  • Reading for this Lecture, LL, 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)

int count 0 do count
System.out.println (count) while (count lt 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 lt 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
Start
do Loop_Body while(Boolean_Expression)
Execute Loop_Body
true
Evaluate Boolean_Expression
false
End loop
6
The 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
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 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.

9
Break in Loops
int count 1 while(count ! 50) count
2 if(count 2 1) break
Write a Comment
User Comments (0)
About PowerShow.com