Download presentation
Presentation is loading. Please wait.
Published byJames Whitehead Modified over 9 years ago
1
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
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
3 Multiple Alternatives (Coins Flowchart)
4
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
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
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
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
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
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
10 Summary of Boolean Operations ab a && b truetruetrue truefalsefalse falsetruefalse falsefalsefalseab a || b truetruetrue truefalsetrue falsetruetrue falsefalsefalse a!atruefalse falsetrue
11
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
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
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
14 The for Loop (cont.) Example int product = 1; for (int i = 1; i <= n; i++) product = product * i;
15
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
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
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
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
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
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
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
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
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"; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.