1 Chapter 7: Advanced Control Flow  Chapter Goals To recognize the correct ordering of decisions in multiple branchesTo recognize the correct ordering.

Slides:



Advertisements
Similar presentations
Control Structures Corresponds with Chapters 3 and 4.
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Computer Science 1620 Loops.
Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.
Computer Science A 4 13/3. Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
1 9/08/06CS150 Introduction to Computer Science 1 Arithmetic Operators.
Computer Science 1620 Programming & Problem Solving.
CS 117 Spring 2002 Repetition Hanly Chapter 4 Friedman-Koffman Chapter 5.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 5: Control Structures II (Repetition)
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Fundamentals of Python: From First Programs Through Data Structures
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Fundamentals of Python: First Programs
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
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.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Chapter 4 Selection Structures: Making Decisions.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
CONTROLLING PROGRAM FLOW
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
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.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
1 Chapter 4: Basic Control Flow ► Chapter Goals  To be able to implement decisions using if statements  To understand statement blocks  To learn how.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Input Validation 10/09/13. Input Validation with if Statements You, the C++ programmer, doing Quality Assurance (by hand!) C++ for Everyone by Cay Horstmann.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
Program Control Flow: Making Decision
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Selected Topics From Chapter 6 Iteration
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Lesson #5 Repetition and Loops.
Repetition Control Structure
Control Structures Part 1
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
do/while Selection Structure
Presentation transcript:

1 Chapter 7: Advanced Control Flow  Chapter Goals To recognize the correct ordering of decisions in multiple branchesTo recognize the correct ordering of decisions in multiple branches To program conditions using Boolean operators and variablesTo program conditions using Boolean operators and variables To understand nested branches and loopsTo understand nested branches and loops To be able to program loops with the for and do/while statementsTo be able to program loops with the for and do/while statements To learn how to process character, word, and line inputTo learn how to process character, word, and line input To learn how to read input from a file through redirectionTo learn how to read input from a file through redirection To implement approximations and simulationsTo implement approximations and simulations

2 Multiple Alternatives  By using collections of if/else statements, a program can distinguish between multiple alternatives.  Example: The user enters the name of a coin, and the program returns the value. This program has five alternatives to choose from: "penny""penny" "nickel""nickel" "dime""dime" "quarter""quarter" erroneous inputerroneous input The order that the alternatives are checked is unimportant

3 Multiple Alternatives (Coins Flowchart)

4 Multiple Alternatives (coins6.cpp) 01: #include 02: 03: #include 04: 05: using namespace std; 06: 07: int main() { 09: cout > name; 12: double value = 0; 13: 14: if (name == "penny") 15: value = 0.01; 16: else if (name == "nickel") 17: value = 0.05; 18: else if (name == "dime") 19: value = 0.10; 20: else if (name == "quarter") 21: value = 0.25; 22: else 23: cout 02: 03: #include 04: 05: using namespace std; 06: 07: int main() { 09: cout > name; 12: double value = 0; 13: 14: if (name == "penny") 15: value = 0.01; 16: else if (name == "nickel") 17: value = 0.05; 18: else if (name == "dime") 19: value = 0.10; 20: else if (name == "quarter") 21: value = 0.25; 22: else 23: cout << name << " is not a valid coin name\n"; 24: cout << "Value = " << value << "\n"; 25: 26: return 0; 26: return 0; 27: } 27: }

5 Multiple Alternatives  In some cases, the order of the tests is important.  Example: A program that displays a description of the likely impact of an earthquake based on its magnitude on the Richter scale. Note that the order of the tests ensures that the right results are printed (see following code).Note that the order of the tests ensures that the right results are printed (see following code). Note that the if/else/else structure ensures the alternatives are exclusive. Independent if statements may cause a single input to print several messages.Note that the if/else/else structure ensures the alternatives are exclusive. Independent if statements may cause a single input to print several messages.

6 Multiple Alternatives (richter.cpp) #include #include using namespace std; int main() { cout > richter; if (richter >= 8.0) cout = 7.0) cout = 6.0) cout = 4.5) cout = 3.5) cout = 0) cout #include using namespace std; int main() { cout > richter; if (richter >= 8.0) cout = 7.0) cout = 6.0) cout = 4.5) cout = 3.5) cout = 0) cout << "Generally not felt by people\n"; else cout << "Negative numbers are not valid\n"; return 0; }

7 Nested Branches  The two-level decision process is reflected in two levels of if statements.  We say the income test is nested inside the test for filing status. More complicated decisions may require deeper levels of nesting.

8 Nested Branches (tax.cpp)  Example: if (marital_status == "s“) { if (income <= SINGLE_LEVEL1) tax = RATE1 * income; else if (income <= SINGLE_LEVEL2) tax = SINGLE_TAX1 + RATE2 * (income - SINGLE_LEVEL1); else tax = SINGLE_TAX2 + RATE3 * (income - SINGLE_LEVEL2); } else { if (income <= MARRIED_LEVEL1) tax = RATE1 * income; else if (income <= MARRIED_LEVEL2) tax = MARRIED_TAX1 + RATE2 * (income - MARRIED_LEVEL1); else tax = MARRIED_TAX2 + RATE3 * (income - MARRIED_LEVEL2); } if (marital_status == "s“) { if (income <= SINGLE_LEVEL1) tax = RATE1 * income; else if (income <= SINGLE_LEVEL2) tax = SINGLE_TAX1 + RATE2 * (income - SINGLE_LEVEL1); else tax = SINGLE_TAX2 + RATE3 * (income - SINGLE_LEVEL2); } else { if (income <= MARRIED_LEVEL1) tax = RATE1 * income; else if (income <= MARRIED_LEVEL2) tax = MARRIED_TAX1 + RATE2 * (income - MARRIED_LEVEL1); else tax = MARRIED_TAX2 + RATE3 * (income - MARRIED_LEVEL2); } cout << "The tax is $" << tax << "\n"; cout << "The tax is $" << tax << "\n";

9 Boolean Operations  An operator that combines test conditions is called a logical operator.  The && (and) operator combines several tests into a new test that passes only when all the conditions are true. Example: if (now.get_hours()==homework.get_hours() && now.get_minutes() == homework.get_minutes()) && now.get_minutes() == homework.get_minutes()) cout << "The homework is due right now!\n"; cout << "The homework is due right now!\n";  The || (or) operator combines two or more conditions and succeeds if at least one of the conditions is true. Example: if (state == "HI" || state == "AK") shipping_charge = 10.00; shipping_charge = 10.00;

10 Summary of Boolean Operations ab a && b truetruetrue truefalsefalse falsetruefalse falsefalsefalseab a || b truetruetrue truefalsetrue falsetruetrue falsefalsefalse a!atruefalse falsetrue

11 Examples of boolean Expressions  The value of x is in interval [3, 10] (x >= 3 && x = 3 && x <= 10)  The value of x is outside the interval [3, 10] (x 10)  An alternative for previous is: !(x >= 3 && x = 3 && x <= 10)

12 DeMorgan's Law  DeMorgan's Law has two forms: !(A && B) is the same as !A || !B!(A && B) is the same as !A || !B !(A || B) is the same as !A && !B!(A || B) is the same as !A && !B  Pay particular attention to the fact that the && and || operators are reversed by moving the not inwards.  Example: state != "AK" && state != "HI" is the same as is the same as !(state == "AK") && !(state == "HI") which is the same as !(state == "AK" || state == "HI")

13 The for Loop  The most common loop has the form i = start; while (i <= end) {... i++; } Because this loop is so common, there is a special form for it. for (i = start; i <= end; i++) { … }

14 The for Loop (cont.)  Example int product = 1; for (int i = 1; i <= n; i++) product = product * i;

15 The for Loop Syntax  General syntax of for loop for (init_expression; condition; update_expression) for (init_expression; condition; update_expression) statement (loop body) statement (loop body) Example: for (int i = 1; i <= 10; i++) sum = sum + i;  Purpose: Execute the initialization statement. While the condition remains true, execute the statement and update the expression.

16 Example of for loop (n!) #include #include using namespace std; int main() { cout << "Please enter a number: "; int n; cin >> n; int product = 1; for (int i = 1; i <= n; i++) { product = product * i; } cout << n << "! = " << product << "\n"; return 0; }

17 The do Loop  Sometimes you want to execute the body of a loop at least once and perform the loop test after the body was executed.  The do/while loop serves that purpose.  General format or syntax is: do { do { statements … loop body statements … loop body } while (condition); } while (condition);  Example: do { xold = xnew; xold = xnew; xnew = (xold + a / xold) / 2; xnew = (xold + a / xold) / 2; } while (fabs(xnew - xold) > EPSILON);

18 Flowchart for do loop do { xold = xnew; xnew = (xold + a / xold) / 2; } while (fabs(xnew - xold)>EPSILON); Purpose : Purpose : 1.Execute the statement inside the loop (loop body). 2.Then test the condition. 3.If the condition is true, repeat the previous two steps.

19 Example of do Loop // Computes an approximate value of the square root // Computes an approximate value of the square root // of a number given as input. // of a number given as input. #include #include #include using namespace std; int main() { cout > a; const double EPSILON = 1E-14; double xnew = a; double xold; do { xold = xnew; xnew = (xold + a / xold) / 2; } while (fabs(xnew - xold) > EPSILON); cout using namespace std; int main() { cout > a; const double EPSILON = 1E-14; double xnew = a; double xold; do { xold = xnew; xnew = (xold + a / xold) / 2; } while (fabs(xnew - xold) > EPSILON); cout << "The square root is " << xnew << "\n"; return 0; }

20 Nested Loops  How can we print a table of values?  For example, this table tells you the fate of $10,000 invested under various interest rates for a different number of years.

21 Nested Loops (cont)  Here is the pseudocode: print table header double rate; for (rate = RATE_MIN; rate <= RATE_MAX; rate = rate + RATE_INCR) { print table row }  How do we print a table row? You need to program another loop. int year; for (year = YEAR_MIN; year <= YEAR_MAX; year = year + YEAR_INCR) { balance = future_value(initial_balance, rate, balance = future_value(initial_balance, rate, year); cout << setw(10) << balance; } year); cout << setw(10) << balance; }

22 Nested Loops (cont)  It's a good idea to print the table header as a loop as well. cout << "Rate "; int year; for (year = YEAR_MIN; year <= YEAR_MAX; year = year + YEAR_INCR) { cout << setw(2) << year << " years"; } << " years"; }  Once everything is put together, you have the loop printing a single row nested in the loop that traverses the interest rates.

23 Part of the Program… … /* print table header */ cout << " Rate "; int year; for (year = YEAR_MIN; year <= YEAR_MAX; year = year + YEAR_INCR) { cout << setw(2) << year << " years "; } cout << "\n"; cout << fixed << setprecision(2); double rate; double initial_balance = 10000; for (rate = RATE_MIN; rate <= RATE_MAX; rate = rate + RATE_INCR) { /* print table row */ int year; cout << setw(5) << rate; for (year = YEAR_MIN; year <= YEAR_MAX; year = year + YEAR_INCR) { double balance = initial_balance * pow(1 + rate / 100, year); cout << setw(10) << balance; } cout << "\n"; } /* print table header */ cout << " Rate "; int year; for (year = YEAR_MIN; year <= YEAR_MAX; year = year + YEAR_INCR) { cout << setw(2) << year << " years "; } cout << "\n"; cout << fixed << setprecision(2); double rate; double initial_balance = 10000; for (rate = RATE_MIN; rate <= RATE_MAX; rate = rate + RATE_INCR) { /* print table row */ int year; cout << setw(5) << rate; for (year = YEAR_MIN; year <= YEAR_MAX; year = year + YEAR_INCR) { double balance = initial_balance * pow(1 + rate / 100, year); cout << setw(10) << balance; } cout << "\n"; }