Repetition-Sentinel,Flag Loop/Do_While

Slides:



Advertisements
Similar presentations
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Advertisements

COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 6, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Chapter 5: Control Structures II (Repetition)
What is the out put #include using namespace std; void main() { int i; for(i=1;i
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From the Ground Up
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 4 Repetition Structures
Java Fundamentals 4.
CSC111 Quick Revision.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
EKT120 COMPUTER PROGRAMMING
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Repetition-Counter control Loop
CiS 260: App Dev I Chapter 4: Control Structures II.
Java Programming: Guided Learning with Early Objects
Chapter 2.2 Control Structures (Iteration)
Chapter 5: Control Structures II
CSS161: Fundamentals of Computing
Control Statements Loops.
Chapter 2.2 Control Structures (Iteration)
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Chapter 5: Control Structures II (Repetition)
Control Statements Loops.
Chapter 4 Repetition Structures
Presentation transcript:

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

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

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: 1 3 6 4 9 12 3 5 -1

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

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);

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"); } }

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);

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;

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;

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 } }

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

Example: Number Guessing Game Write a program that generates a random number in the range 0..100. 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.

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

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

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

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;

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 }

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.

Difference while Loop do…while Loop for Loop

Example SECRET_CODE = 1234 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

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.

do…while Loop (Post-Test Loop)

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

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

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 1 2 3 4

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.

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 1 2 3 4 6 7 8 9 10

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");

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

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)

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

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: * ** *** **** *****

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.

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: * ** *** **** *****

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 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50

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