Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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 <= 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 <= 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 > 0:"); min=Keyboard.readInt(); max=Keyboard.readInt(); } while (min <= 0 || max < =0); for (int count = min; count <= 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


Download ppt "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."

Similar presentations


Ads by Google