Loops Control Flow (Order of Execution) 5.2 the While Loop While

Loops Control Flow (Order of Execution) 5.2 the While Loop While

Control Flow Loops (order of execution) • So far, control flow in our programs has included: Unit 4 ‣ sequential processing (1st statement, then 2nd statement…) Sections 5.2-12 ‣ branching (conditionally skip some statements). CS 1428 • Chapter 5 introduces loops, which allow us to Fall 2017 conditionally repeat execution of some statements. Jill Seaman ‣ while loop ‣ do-while loop ‣ for loop 1 2 5.2 The while loop while syntax and semantics l As long as the relational expression is true, repeat • The while statement is used to repeat the statement statements: while (expression) statement • How it works: ‣ expression is evaluated: ‣ If it is true, then statement is executed, then it starts over (and expression is evaluated again). ‣ If it is false, then statement is skipped (and the loop is done). 3 4 while example 5.3 Using while for input validation • Example: • Inspect user input values to make sure they are Hand trace! valid. int number = 1; • If not valid, ask user to re-enter value: while (number <= 3) { int number; This expression is true when cout << “Student” << number << endl; number is OUT of range. number = number + 1; cout << “Enter a number between 1 and 10: “; } cin >> number; Explain the valid values in the prompt cout << “Done” << endl; while (number < 1 || number > 10) { cout << “Please enter a number between 1 and 10: “; cin >> number; } Don’t forget to input • Output Student1 the next value Student2 // Do something with number here Student3 Done 5 6 Input Validation 5.4 Counters l Checking for valid characters: l Counter: a variable that is incremented (or char answer; decremented) each time a loop repeats. cout << “Enter the answer to question 1 (a,b,c or d): “; cin >> answer; l Used to keep track of the number of iterations while (answer != ‘a’ && answer != ‘b’ && (how many times the loop has repeated). answer != ‘c’ && answer != ‘d’) { cout << “Please enter a letter a, b, c or d: “; cin >> answer; } l Must be initialized before entering loop!!!! // Do something with answer here 7 8 Counters Counters l Example (how many times does the user enter l Example, using the counter to control how an invalid number?): many times the loop iterates: cout << “Number Number Squared” << endl; int number; cout << “------ --------------” << endl; int count = 0; cout << “Enter a number between 1 and 10: “; int num = 1; // counter variable cin >> number; while (num <= 8) { cout << num << “ “ << (num * num) << endl; while (number < 1 || number > 10) { num = num + 1; // increment the counter count = count + 1; cout << “Please enter a number between 1 and 10: “; } cin >> number; } Number Number Squared ------ -------------- cout << count << “ invalid numbers were entered.“ << endl; l Output: 1 1 // Do something with number here 2 4 3 9 4 16 5 25 6 36 9 7 49 10 8 64 5.5 The do-while loop do-while syntax and semantics l Execute the statement(s), then repeat as long as • The do-while loop has the test expression at the relational expression is true. the end: Don’t forget the do semicolon at the end statement while (expression); • How it works: ‣ statement is executed. ‣ expression is evaluated: ‣ If it is true, then it starts over (and statement is executed again). ‣ If (when) it is false, the loop is done. 11 • statement always executes at least once. 12 do-while example do-while with menu char choice; • Example: do { cout << “A: Make a reservation.” << endl; int number = 1; cout << “B: View flight status.” << endl; do cout << “C: Check-in for a flight.” << endl; { cout << “D: Quit the program.” << endl; cout << “Student” << number << endl; cout << “Enter your choice: “; number = number + 1; } while (number <= 3); cin >> choice; cout << “Done” << endl; switch (choice) { case ‘A’: // code to make a reservation break; case ‘B’: // code to view flight status • Output Student1 break; Student2 case ‘C’: // code to process check-in Student3 break; Done } 13 } while(choice != ‘D’); 14 Different ways to control the loop 5.6 The for loop • The for statement is used to easily implement a l Conditional loop: body executes as long as a count-controlled loop. certain condition is true ‣ input validation: loops as long as input is invalid for (expr1; expr2; expr3) statement l Count-controlled loop: body executes a specific number of times using a counter • How it works: 1. expr1 is executed (initialization) ‣ actual count may be a literal, or stored in a variable. 2. expr2 is evaluated (test) l Count-controlled loop follows a pattern: 3. If it is true, then statement is executed, ‣ initialize counter to zero (or other start value). then expr3 is executed (update), then go to step 2. ‣ test counter to make sure it is less than count. 4. If (when) it is false, then statement is skipped ‣ update counter during each iteration. 15 (and the loop is done). 16 The for loop flow chart The for loop and the while loop for (expr1; expr2; expr3) • The for statement statement for (expr1; expr2; expr3) statement • expr1 is equivalent to the following code using a while statement: expr1; // initialize while (expr2) { // test expr2 statement expr3 statement expr3; // update } 17 18 for loop example Counters: redo l Example, using the counter to control how • Example: Equivalent to number = number + 1 many times the loop iterates: cout << “Number Number Squared” << endl; int number; cout << “------ --------------” << endl; for (number = 1; number <= 3; number++) { int num = 1; // counter variable cout << “Student” << number << endl; while (num <= 8) { Note: no semicolon cout << num << “ “ << (num * num) << endl; } num = num + 1; // increment the counter } cout << “Done” << endl; l Rewritten using a for loop: cout << “Number Number Squared” << endl; • Output Student1 cout << “------ --------------” << endl; Student2 Student3 int num; Done for (num = 1; num <= 8; num++) cout << num << “ “ << (num * num) << endl; 19 20 Define variable in init-expr User-controlled count • You may define the loop counter variable inside • You may use a value input by the user to the for loop’s initialization expression: control the number of iterations: int maxCount; for (int x = 10; x > 0; x=x-2) Hand trace! cout << “How many squares do you want?” << endl; cout << x << endl; cin >> maxCount; cout << x << endl; //ERROR, can’t use x here cout << “Number Number Squared” << endl; cout << “------ --------------” << endl; for (int num = 1; num <= maxCount; num++) • Do NOT try to access x outside the loop cout << num << “ “ << (num * num) << endl; (the scope of x is the for loop statement ONLY) • What is the output of the for loop? • How many times does the loop iterate? 21 22 The exprs in the for are optional Loops in C++ (review) statement may be a • You may omit any of the three exprs in the for • while while (expression) compound statement loop header statement (a block: {statements}) int value, incr; ‣ if expression is true, statement is executed, repeat cout << “Enter the starting value: “; cin >> value; • for for (expr1; expr2; expr3) statement for ( ; value <= 100; ) { ‣ equivalent to: expr1; cout << “Please enter the next increment amount: “; while (expr2) { cin >> incr; statement value = value + incr; expr3; cout << value << endl; } } • do while • Style: use a while loop for something like this. do statement is executed. statement if expression is true, then repeat while (expression); • When expr2 is missing, it is true by default.23 24 Common tasks solved Counting using loops (review) l set a counter variable to 0 l Counting l increment it inside the loop (each iteration) l Summing l after each iteration of the loop, it stores the # of l Calculating an average (the mean value) loop iterations so far l int number; Read input until “sentinel value” is encountered int count = 0; cout << “Enter a number between 1 and 10: “; l Read input from a file until the end of the file is cin >> number; encountered while (number < 1 || number > 10) { count = count + 1; cout << “Please enter a number between 1 and 10: “; cin >> number; } cout << count << “ invalid numbers entered “ << endl; // Do something with number here 25 26 5.7 Keeping a running total Keeping a running total (summing) l After each iteration of the loop, it stores the sum • Output: of the numbers added so far (running total) How many days did you ride you bike? 3 l set an accumulator variable to 0 Enter the miles for day 1: 14.2 Enter the miles for day 2: 25.4 l Enter the miles for day 3: 12.2 add the next number to it inside the loop Total miles ridden: 51.8 int days; //Count for count-controlled loop float total = 0.0; //Accumulator float miles; //daily miles ridden cout << “How many days did you ride your bike? “; cin >> days; • How would you calculate the average mileage? for (int i = 1; i <= days; i++) { cout << “Enter the miles for day “ << i << “: ”; cin >> miles; total = total + miles; } total is 0 first time through cout << “Total miles ridden: “ << total << endl; 27 28 5.8 Sentinel controlled loop Sentinel example l sentinel: special value in a list of values that • Example: indicates the end of the data float total = 0.0; //Accumulator float miles; //daily miles ridden l sentinel value must not be a valid value! cout << “Enter the miles you rode on your bike each day, “; -99 for a test score, -1 for miles ridden cout << “then enter -1 when finished. “ << endl; cin >> miles; //priming read l User does not need to count how many values while (miles != -1) { total = total + miles; //skipped when miles==-1 will be entered cin >> miles; //get the next one } l Requires a “priming read” before the loop starts cout << “Total miles ridden: “ << total << endl; ‣ so the sentinel is NOT included in the sum Enter the miles you rode on your bike each day, • Output: then enter -1 when finished.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    11 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us