Presentation is loading. Please wait.

Presentation is loading. Please wait.

Repetition-Sentinel,Flag Loop/Do_While

Similar presentations


Presentation on theme: "Repetition-Sentinel,Flag Loop/Do_While"— Presentation transcript:

1 Repetition-Sentinel,Flag Loop/Do_While
Chapter 4: Control Structures Repetition-Sentinel,Flag Loop/Do_While

2 Sentinel-Controlled Loop
Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known. The idea of a sentinel controlled loop is that there is a special value (the "sentinel") that is used to say when the loop is done. General form: Input the first data item into variable Loop while (variable != sentinel) . input a data item into variable; End loop

3 Example Write a program that adds up a list of positive numbers entered by the user from the keyboard, then prints the result. What is the number of iterations ?? Unknown Since the input are positive integers, we can use (-1) as the sentinel. Example of user input:

4 Solution sum number start sum = 0 Read number number != -1 No
Start Program sum = 0 Read number loop while (number != -1) sum = sum + number End loop Print sum End Program start sum = 0 Read number number != -1 No Print sum sum 5 number sum= sum+ number Yes Input 5 2 3 -1 Read number 5 2 7 3 end 10 -1 Print sum  10

5 Sentinel-Controlled while Loop Example 5-4
//Sentinel-controlled while loop import java.util.*; public class SentinelControlledWhileLoop { static Scanner console = new Scanner(System.in); static final int SENTINEL = -999; public static void main (String[] args) { int number; //variable to store the number int sum = 0; //variable to store the sum int count = 0; //variable to store the total //numbers read System.out.println("Enter positive integers " "ending with " + SENTINEL);

6 Sentinel-Controlled while Loop Example 5-4 (continued)
number = console.nextInt(); while (number != SENTINEL) { sum = sum + number; count++; number = console.nextInt(); } System.out.printf("The sum of the %d " "numbers = %d%n", count, sum); if (count != 0) System.out.printf("The average = %d%n",(sum / count)); else System.out.println("No input"); } }

7 Sentinel-Controlled while Loop Example 5-5
//This program converts uppercase letters to their // corresponding telephone digits. //******************************************************** import java.util.*; public class TelephoneDigit { static Scanner input = new Scanner (System.in); public static void main (String[] args) { char letter; String inputMessage; String inputString; String outputMessage; inputMessage = "Program to convert uppercase " "letters to their corresponding " "telephone digits.\n" "To stop the program enter #.\n" "Enter a letter:"; System.out.println(inputMessage);

8 Sentinel-Controlled while Loop Example 5-5 (continued)
letter = input.next().charAt(0); while (letter != '#' ) { outputMessage = "The letter you entered is: " + letter + "\n" + "The corresponding telephone " + "digit is: "; if (letter >= 'A' && letter <= 'Z') { switch (letter) { case 'A': case 'B': case 'C': outputMessage = outputMessage+ "2"; break; case 'D': case 'E': case 'F': outputMessage = outputMessage+ "3"; break;

9 Sentinel-Controlled while Loop Example 5-5 (continued)
case 'G': case 'H': case 'I': outputMessage = outputMessage+ "4"; break; case 'J': case 'K': case 'L': outputMessage = outputMessage+ "5"; break; case 'M': case 'N': case 'O': outputMessage = outputMessage+ "6"; break; case 'P': case 'Q': case 'R': case 'S': outputMessage = outputMessage + "7"; break;

10 Sentinel-Controlled while Loop Example 5-5 (continued)
case 'T': case 'U': case 'V': outputMessage = outputMessage+ "8"; break; case 'W': case 'X': case 'Y': case 'Z': outputMessage = outputMessage+ "9"; } } else outputMessage = outputMessage + "Invalid input"; System.out.println(outputMessage); inputMessage = "Enter another uppercase letter " "to find its corresponding " "telephone digit.\n" "To stop the program enter #.\n" "Enter a letter:"; System.out.println (inputMessage); letter = input.next().charAt(0); }//end while } }

11 Flag-Controlled Loop General form:
A flag is a boolean variable, used to indicate whether or not a desired situation has occurred A value of FALSE indicates that the desired event has not yet occurred TRUE indicates that it has occurred General form: boolean found = false Loop while (!found) . if (expression) found = true End loop Initialization Testing Updating

12 Example: Number Guessing Game
Write a program that generates a random number in the range Then the user tries to guess the number. If the user guessed the number correctly, then print the message “You guessed the number correctly !”. Otherwise: If the guessed number is less than the random number, print message “Your guess is lower than the number”. Otherwise: print message “Your guess is higher than the number”. The user enters another number. The user guesses until he\she enters the correct number.

13 Solution Start Program randomNumber = …  will be discussed later guessedRight = false loop while (not guessedRight) Read guess if (guess = randomNumber) guessedRight = true Print “You guessed the number correctly !” else if (guess < randomNumber) Print “Your guess is lower than the number” Print “Your guess is higher than the number” End loop End Program

14 guess < randomNumber
start Solution randomNumber = … guessedRight = false Not guessedRight Yes No Read guess guess = randomNumber Yes No guessedRight = true guess < randomNumber Yes Print “Correct Guess” No Print “Guess is Lower” Print “Guess is Higher” end

15 Flag-Controlled while Loop
Boolean value used to control loop. General form: boolean found = false; while (!found) { . if (expression) found = true; }

16 Flag-Controlled while Loop- Example 5-6
/Flag-controlled while loop. //Guessing the number game. import java.util.*; public class FlagControlledLoop { static Scanner console = new Scanner(System.in); public static void main (String[] args) { //declare the variables int num; //variable to store the random number int guess; //variable to store the number //guessed by the user boolean done; //boolean variable to control the loop num = (int) (Math.random() * 100); done = false;

17 while (!done) { System.out.print ("Enter an integer greater" " than or equal to 0 and " "less than 100: "); guess = console.nextInt(); System.out.println(); if (guess == num) { System.out.println("You guessed the " "correct number."); done = true; } else if (guess < num) System.out.println("Your guess is " "lower than " "the number.\n" "Guess again!"); else System.out.println("Your guess is “ + "higher than " "the number.\n" "Guess again!"); } //end while }

18 The do…while Loop Form:
statement(s) while (expression) Statements are executed first and then expression is evaluated. Statements are executed at least once and then continued if expression is true.

19 Difference while Loop do…while Loop for Loop

20 Example SECRET_CODE = do Print "Type the secret code number to enter." Read code while (code!=SECRET_CODE) Print "Well done, you can now enter" SECRET_CODE = 1234 Print input msg Read code code != SECRET_CODE Yes No Print msg

21 The do…while Loop (Repetition) Structure
Syntax: do statement while (expression); Statements are executed first and then expression is evaluated. Statements are executed at least once and then continued if expression is true.

22 do…while Loop (Post-Test Loop)

23 do…while Loop (Post-Test Loop)
Example : i = 0 ; do { System.out.print(i + “ “ ) ; i = i + 5 ; } while ( i <= 30 ) ; output :

24 break Statements Used to Can be placed within if statement of a loop.
exit early from a loop. (while, for, and do...while) skip remainder of switch structure. Can be placed within if statement of a loop. If condition is met, loop is exited immediately. After the break statement executes, the program continues to execute with the first statement after the structure

25 break Statements Output 1 2 3 4
Example : int count ; for ( count = 1 ; count <= 10 ; count ++ ) { if ( count == 5) break ; System.out.print(count + “ ” ); } Output

26 continue Statements Used in while, for, and do...while structures.
When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop. When executed in a while/do…while structure, expression is evaluated immediately after continue statement. In a for structure, the update statement is executed after the continue statement; the loop condition then executes.

27 continue Statements Output 1 2 3 4 6 7 8 9 10
Example : int count ; for ( count = 1; count <= 10 ; count ++ ) { if ( count == 5) continue; System.out.print(count + “ ” ); } Output

28 break and continue example (for loop)
System.out.println ("starting loop:"); for (int x=0 ; x < 7; x++) { System.out.println ("in loop " + x); if (x == 2) continue; System.out.println (" survived continue"); if (x == 4) break; System.out.println (" survived break"); } // end of for // break out of loop System.out.println ("end of loop or exit using break");

29 break and continue example
Output: starting loop: in loop 0 survived continue survived break in loop 1 in loop 2 in loop 3 in loop 4 end of loop or exit using break

30 break and continue example
int i = 0; while(true) { i++; if(i == 100) break; // Out of loop if(i % 10 != 0) continue;// Top of loop (condition) System.out.println(i); } This is an infinite loop that keeps printing the value of i if it is divisible by 10. We will exit the loop only when ( i==100)

31 Nested loop: loop in loop
Example: Print the following using loops. * ** *** **** ***** 5 rows : Row 1  1 star Row 2  2 stars Row 5  5 stars We need a loop for the rows We need loops for columns The number of stars in a row is equal to the row# Need nested loop Since the # of iterations are known  for loops

32 Nested loop: loop in loop
Solution: For (i = 1 to 5, step 1) For (j = 1 to i, step 1) print(" *") End For move cursor to next line End Forutput: * ** *** **** *****

33 Nested Control Structures
Provides new power, subtlety, and complexity. if, if…else, and switch structures can be placed within while loops. for loops can be found within other for loops.

34 Nested Control Structures (Example 5-18)
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); } Output: * ** *** **** *****

35 Nested Control Structures (Example 5-19)
//printing a multiplication table for (i = 1; i <= 5; i++) { for (j = 1; j <= 10; j++) System.out.printf("%3d", i*j); System.out.println(); } Output

36 Chapter Summary Looping mechanisms: Nested control structures
Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop for loop do…while loop break statements continue statements Nested control structures


Download ppt "Repetition-Sentinel,Flag Loop/Do_While"

Similar presentations


Ads by Google