while - PowerPoint PPT Presentation

About This Presentation
Title:

while

Description:

The entire construct is called a while loop. statements are executed until condition is true. Even before executing it the first time condition is evaluated ... – PowerPoint PPT presentation

Number of Views:53
Avg rating:3.0/5.0
Slides: 14
Provided by: RMK
Category:
Tags: construct

less

Transcript and Presenter's Notes

Title: while


1
while
  • while (condition)
  • statements
  • Can put anything in statements
  • The entire construct is called a while loop
  • statements are executed until condition is true
  • Even before executing it the first time condition
    is evaluated
  • A while loop may not execute even once

2
Example
  • class justAnExample
  • public static void main(String arg)
  • int x 5
  • int y 0
  • while (x lt 10)
  • y--
  • x
  • System.out.println(y)

3
Example
  • class justAnExample
  • public static void main(String arg)
  • int x 15
  • int y 0
  • while (x lt 10)
  • y--
  • x
  • System.out.println(y)

4
Sum of natural numbers
  • class naturalSum
  • public static void main(String arg)
  • int n 2
  • int y 1
  • while (n lt 100)
  • y n
  • n
  • System.out.println(Sum of the first
    (n-1) natural numbers is y)

5
Sum of natural numbers
  • class naturalSumAnotherWay
  • public static void main(String arg)
  • int n 99
  • int m n1
  • int y 100
  • while (n gt 0)
  • y n
  • n--
  • System.out.println(Sum of the first
    m natural numbers is y)

6
do-while
  • do
  • statements
  • while (condition)
  • statements execute at least once irrespective
    of condition

7
for loops
  • for (expression1 condition expression2)
  • statements
  • Same as
  • expression1
  • while (condition)
  • statements
  • expression2

8
Sum of natural numbers
  • class naturalSum
  • public static void main(String arg)
  • int n
  • int y 1
  • for (n2 n lt100 n)
  • y n
  • System.out.println(Sum of the first
    (n-1) natural numbers is y)

9
Comma operator in for loop
  • for (expression1a, expression2a, condition
    expression1b, expression2b,)
  • statements
  • Same as
  • expression1a
  • expression2a
  • while (condition)
  • statements
  • expression1b
  • expression2b

10
Sum of natural numbers
  • class naturalSum
  • public static void main(String arg)
  • int n
  • int y
  • for (n2, y1 n lt100 y n, n)
  • System.out.println(Sum of the first
    (n-1) natural numbers is y)

11
Empty for loop body
  • for (expression1 condition expression2)
  • Same as
  • for (expression1 condition expression2)

12
Infinite loops
  • Loops that never terminate
  • while (true)
  • statements
  • do
  • statements
  • while (true)

13
Infinite loops
  • for (expression1 expression2)
  • statements
  • for (i0 i gt -10 i)
  • statements
  • for (i0 ilt100 i--)
  • statements
Write a Comment
User Comments (0)
About PowerShow.com