Three kinds of looping structures PowerPoint PPT Presentation

presentation player overlay
About This Presentation
Transcript and Presenter's Notes

Title: Three kinds of looping structures


1
Three kinds of looping structures
  • The while loop
  • The for loop
  • The do (also called the do-while) loop
  • All have equivalent power, e.g., if you can write
    the program using a do loop you could also write
    the program using a for loop

2
A simple while loop example
  • public class Sum
  • public static void main( String args)
  • final int MIN 1, MAX 100
  • int count MIN, sum 0
  • while (count lt MAX)
  • sum count
  • count
  • System.out.println("the sum of the
    number between "
  • MIN " and " MAX " is "
    sum)

3
Equivalent for loop
  • public class Sum
  • public static void main( String args)
  • final int MAX 100, MIN 1
  • int sum 0
  • for (int count MIN count lt MAX count)
  • sum count
  • System.out.println("the sum of the
    number between "
  • MIN " and " MAX " is "
    sum)

4
A do loop example
  • import cs1.Keyboard
  • public class Sum
  • public static void main( String args)
  • int min, max, sum 0
  • do
  • System.out.print(enter limits for the sum")
  • System.out.println(" both must gt 0")
  • minKeyboard.readInt()
  • maxKeyboard.readInt()
  • while (min lt 0 max lt 0)
  • for (int count min count lt max count)
  • sum count

5
Choosing a looping structure --- rule of thumb
guidelines
  • Use a do loop or a while loop when the number of
    iterations can not be known in advance
  • Use a for loop for counting
  • Use a do loop when the body of the loop must be
    executed before evaluating the loop test

6
A silly game version 1
  • import cs1.Keyboard
  • public class Guess
  • public static void main( String args)
  • final int MYNUMBER 3
  • System.out.print("guess a number between 1
    10 ")
  • int guess Keyboard.readInt()
  • if (guess MYNUMBER)
  • System.out.println("You got it!!!")
  • else
  • System.out.println("Sorry, that's wrong")

7
A silly game version 2
  • import cs1.Keyboard
  • public class Guess
  • public static void main( String args)
  • final int MYNUMBER 3
  • int guess
  • do
  • System.out.print("guess between 1 10 ")
  • guess Keyboard.readInt()
  • if (guess MYNUMBER)
  • System.out.println("You got it!!!")
  • else
  • System.out.println("Sorry, that's wong")
  • while (guess ! MYNUMBER)

8
A silly game version 3
  • Add a loop to repeat the game in class
Write a Comment
User Comments (0)
About PowerShow.com