Download presentation
Presentation is loading. Please wait.
1
Program Control Flow: Making Decision
CHAPTER 4B Program Control Flow: Making Decision
2
Chapter GOAL: To be able to implement decisions using if /else statements To understand statement blocks To learn how to apply relational and logical operator, (compare integers, floating-point numbers). To develop strategies for processing input and handling errors To understand the Boolean data type To avoid infinite loops and off-by-one errors To recognize the correct ordering of decisions in multiple branches if/else-if switch
3
4.1 The if Statement Syntax 1: if statement if (condition) statement
Example: if (x >= 0) y = sqrt(x); Purpose: Execute the statement if the condition is true. Syntax 2: block statement { statement1; statement2; … statementn; } Example: { double length = sqrt(area); cout << area << “\n”; Purpose: Group several statements into a block that can be controlled by another statement..
4
4.1 The if Statement Usage: implement a decision
It has two parts: a test and a body. Ex: Multiple statements can be grouped together in a block statement by enclosing them in braces { }: area <0? Print message false true if (area < 0) cout << “Error: Negative area. \n”; if (area < 0) { cout << “Error: Negative area. \n”; return 1; }
5
4.1 The if Statement Example: If the area is negative, then print an error message and returns an error code (use return 1 in main()). area1.cpp
6
4.1 The if Statement Exercise:: Write a program that reads in a student’s grade. Prints ‘Passed” if the student’s grade is higher or equal than 60. print “Passed” [grade < 60] [grade >= 60] If single-selection statement activity diagram
7
4.2 The if/else Statement Syntax 3: if/else statement
if (condition) statement1 else statement2 Example: if (x >= 0) y = sqrt(x); else cout <<“Bad input\n”; Purpose: Execute the statement if the condition is true, the second statement if the condition is false.
8
4.2 The if/else Statement The if/else consists of a condition of two alternatives. The first condition is performed is the condition is true. The second condition is performed if the condition is false. The if/else statement is a better choice than a pair of if statements with complementary conditions. area <0? Compute & print root Display error message true false
9
4.2 The if/else Statement area2.cpp
10
4.2 The if/else Statement Exercise:: Write a program that reads in a student’s grade. Prints ‘Passed” if the student’s grade is higher or equal than 60, but prints “Failed” if the student’s grade is less than 60. print “Failed” print “Passed” [grade < 60] [grade >= 60] If …else double-selection statement activity diagram
11
4.2 The if/else Statement Exercise:: Write a program that prints all solutions to the quadratic equation ax2 + bx + c =0. Read in a, b, c and use the quadratic formula. If the discriminant b2-4ac is negative, display a message stating that there are no solutions. Test with these data: a b c x 1 3 2 -1, -2 5 25 -4.877, 6 9 -1, -0.5 No solution
12
4.3 Relational Operators C++ has six relational operators to implement conditions:
13
4.3 Relational Operators Common error: confusing = and ==
Remember!!! Use == inside tests Use = outside tests a = 5; /* assign 5 to a */ if (a == 5) /* test whether a equals to 5 */
14
4.3 Relational & Logic Operator
15
4.4 Boolean Operations: Combine test conditions: Reverse a value: AND && OR NOT ! || && : combines several tests into new test that passes only when ALL the conditions are true? || : combines several conditions and succeeds if AT LEAST ONE of the conditions is true. ! : returns its opposite
16
4.4 Boolean Operations: The && and || operators are computed using lazy evaluation. The expressions are evaluated from left to right, and evaluation stops as soon as the truth value is determined.
17
4.4 Boolean Operations: Test yourself if ( (2 < x) && (x < 7) )
x = 2 False x = 5 True x = 10 False if ( ( x = = 1) | | ( x = = y) ) x = -1, y = -1 True x = 1, y = 1 True x = y True !( x < y) x = 2, y = 4 False x = 5, y = -2 True x = 1, y = 1 True !(x = = y) x = 2, y = 4 True x = 1, y = 1 False
18
4.4 Relational & Logic Operator
19
EXERCISE Write a program that survey friendship by two questions. Display a conclusion message as below: Question Answer Would you encourage your friends to study? Y N Would you help your friend to cheat in exam? Output message You are not a true friend! You are an angel! You should be a more concerned friend You are a devil!
20
4.5 Input Validation An important application for the if statement
Purpose: verifies the user has given reasonable input. Example: user types "five" and hits return! (Causing cin to fail). GOOD PRACTICE: After every input, test for the failed state: The actual input should also be validated, even if type is correct. double area; cin >> area; if (cin.fail()) { cout << “Error: Bad input\n”; return 1; } if (area < 0)
21
4.5 Input Validation area3.cpp
22
4.5 Input Validation Alternative: if (cin)
/* the stream did not fail */ else /* the stream failed */
23
Modify your program in [2. 7] (Chapter 2 slide no
Modify your program in [2.7] (Chapter 2 slide no. 45) so that the program could be able to validate user input. If input such as “fifty” is inserted, the program display “Bad inputs” and ends the program.
24
4.6 Multiple Alternatives:
if/else-if statement (conditional structure) switch statement (selective structure)
25
4.6 Multiple Alternatives:
if/else-if statement Distinguish between multiple alternatives by using collections of if/else statements Syntax: if (condition1) statement1; else if (condition2) statement2; … else statementN; 1 2 3 4 5 6 7
26
4.6 Multiple Alternatives:
if/else-if statement Example: Telling if the value currently stored in x is positive, negative or none of them (i.e. zero): if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; 1 2 3 4 5 6
27
4.6 Multiple Alternatives:
if/else-if statement if/else-if ensure the alternatives are exclusive. → remaining else-if statement will be ignored once a condition is fulfilled. Independent if statements may cause a single input to print several messages. Consider the example: Month Category 1-3 Winter 4-6 Spring 7-9 Summer 10-12 Autumn winter: december to february spring: march to may summer: june to august fall: september to november
28
4.6 Multiple Alternatives:
Comparison: if/else-if Independent if if (month < 0) cout << “Invalid Input"; else if (month <= 3) cout << “Winter"; else if (month <= 6) cout << “Spring"; else if (month <= 9) cout << “Summer"; else if (month <= 12) cout << “Autumn"; else 1 2 3 4 5 6 7 8 9 10 11 12 if (month < 0) cout << “Invalid Input"; if (month <= 3) cout << “Winter"; if (month <= 6) cout << “Spring"; if (month <= 9) cout << “Summer"; if (month <= 12) cout << “Autumn"; if (month > 12) 1 2 3 4 5 6 7 8 9 10 11 12 What is the output if month is 6?
29
4.6 Multiple Alternatives:
if/else-if statement Since the alternatives are exclusive, therefore order of the condition is important. Considering the previous example with the conditions reversed: if (month <= 12) cout << “Autumn "; else if (month <= 9) cout << “Summer "; else if (month <= 6) cout << “Spring"; else if (month <= 3) cout << “Winter "; else if (month < 0) cout << “Invalid Input"; else 1 2 3 4 5 6 7 8 9 10 11 12 What is the output if month is 6?
30
4.6 Multiple Alternatives:
if/else-if statement Example: (order not important) The user enters the name of a coin, and the program returns the value. Program output: (bold – user input) 1¢ 5¢ Enter coin name: penny Penny equal to $0.01 nickel penny Enter coin name: penn Invalid Input!!! 10¢ 25¢ quarter dime
31
Case 1: Solution Order not important!! coin5.cpp
32
4.6 Multiple Alternatives:
if/else-if statement Example: (order is important) Develop a program that prompt the user for the value of magnitude on the Richter scale and displays a description of 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 Program output: (bold – user input) Enter a magnitude on the Richter scale: 6.5 Many buildings considerably damaged, some collapse.
33
4.6 Multiple Alternatives:
Richter Scale Information: Information: Richter scale is a measurement for the strength of an earth quake. Every step in the scale, for example , signifies a tenfold increase in the strength of the quake. In 2004 Indian Ocean earthquake which kills more than 230,000 casualties rated 9.3 on the Richter scale. Magnitude Earthquake effects ≥ 8.0 Most structures falls 7.0–7.9 Many buildings destroyed 6.0–6.9 Many buildings considerably damaged, some collapse 4.5–5.9 Damage to poorly constructed buildings 3.5–4.4 Felt by many people, no destruction 0–3.3 Generally not felt by people
34
Case 2: (order is important)
richter.cpp
35
Case 2: (order is important)
All +ve values fall into the 1st case!!!
36
4.6 Multiple Alternatives:
if/else-if statement Exercise: Create a program that asks the user to key in any number which is within 1 to 9. The user inputs ‘1’ , for instance, and the program prints the English word “one”. Program output: (bold – user input) Enter a number (1-9): 2 Two Enter a number (1-9): -1 Invalid number Enter a number (1-9): 100 Invalid number
37
4.6 Multiple Alternatives:
if/else-if statement Exercise: Write a program to convert scores to their respective grade according to the below table: Score Grade ≥90 ( ) A ≥80 ( ) B ≥70 ( ) C ≥60 ( ) D <60 (0 - 59) Fail Program output: (bold – user input) Enter your test score(0-100): 75 Your grade is C
38
4.6 Multiple Alternatives:
if/else-if statement Exercise: Create a program that reads the user’s age and then prints “You are a child.” if age < 18, “You are an adult.” if 18 ≤ age < 65, “You are a senior citizen.” if age ≥ 65 Program output: (bold – user input) Enter your age: 44 You are an adult
39
4.6 Multiple Alternatives:
switch statement Compares a single integer value against several constant alternatives → like a sequence of if/else-if Syntax: switch (expression) { case constant1: group of statement1; break; case constant2: group of statement2; ... default: default group of statements; }
40
4.6 Multiple Alternatives:
switch statement Example 1: Test cases must be constant Each branch terminated by break break: loop is immediately terminated, and program control resumes at the next statement following the loop Try remove the break?
41
4.6 Multiple Alternatives:
switch statement Example 2:
42
4.6 Multiple Alternatives:
switch statement Exercise: Create a program that simulates a simple calculator. It reads two integers and a character representing the operation. If the character is “ + ”, the sum is printed; if “ - ”, the difference is printed; if “ * ”, the product is printed; if “ / ”, the quotient is printed; and if it is a %, the remainder is printed. Use a switch statement. Hint: The character should be the control variable for the switch statement. Program output: (bold – user input) Enter two integers: 30 13 Enter an operator (+, -, *, /, %): % Answer: 30 % 13 = 4
43
4.7 Nested Branches: Nested if/else statements can be used when there are two (or more) levels of decision making. Example: Taxes There is a different table for each marital status (decision 1). Once you have found the right table, your are taxed differently according to your income (decision 2).
44
4.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
45
What is the program code?
4.7 Nested Branches: What is the program code? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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); } if (income <= MARRIED_LEVEL1) else if (income <= MARRIED_LEVEL2) tax = MARRIED_TAX1 + RATE2 * (income - MARRIED_LEVEL1); tax = MARRIED_TAX2 + RATE3 * (income - MARRIED_LEVEL2);
46
4.7 Nested Branches: else always belongs to the closest if
COMMON ERROR: The Dangling else problem Example: Postage Rate (Domestic, International) Peninsular Penang International RM 5.00 RM 10.00 RM 20.00 double shipping_charge = 5.00; if(country == "MALAYSIA")//RM5 inside continental Malaysia if (state == "Penang") //Penang is more expensive shipping_charge = 10.00; else //Pitfall shipping_charge = 20.00; //RM20 outside continental else always belongs to the closest if
47
The following algorithm yields the season (Spring, Summer, Fall, or Winter) for a given month and day. Write a program that prompts the user for a month and day and then prints the season, as determined by this algorithm.
48
WAP to print sum of four integers which are key in by the user.
Key in four integers: 3 4 -5 10 Sum is 12 WAP to print maximum integer among four integers which are key in by the user. Key in four integers: 3 4 -5 10 Max is 10
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.