Download presentation
Presentation is loading. Please wait.
1
Chapter 3 Control Statements
DDC 2133 Programming II
2
Objectives To declare bool type and write Boolean expressions using comparison operators . To implement selection control using simple if statements. To combine conditions using logical operators (&&, ||, and !). To implement selection control using if ... else statements. To implement selection control using nested if statements. DDC 2133 Programming II
3
Objectives (cont.) To implement selection control using switch statements. To write expressions using the conditional operator. To display formatted output using the stream manipulators. To know the rules governing operand evaluation order, operator precedence, and operator associativity. DDC 2133 Programming II
4
The bool Type and Operators
Values: true, false C++ provides six relational operators (also known as comparison operators) to compare two values. bool done; bool isGreater; done = false; isGreater = 5 < 3; //isGreater == false DDC 2133 Programming II
5
Comparison Operators DDC 2133 Programming II
6
Simple if Statements if (radius >= 0) {
area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area; } if (booleanExpression) { statement(s); } DDC 2133 Programming II
7
Compound Condition DDC 2133 Programming II
8
Examples Build a program that checks whether a number is even or odd. The program prompts the user to enter an integer and displays “number is even” if it is even and “number is odd” if it is odd. DDC 2133 Programming II
9
#include <iostream> using namespace std; int main() {
int number; cout << "Enter an integer: "; cin >> number; if (number % 2 == 0) cout << number << " is even."; if (number % 2 != 0) cout << number << " is odd."; return 0; } DDC 2133 Programming II
10
Caution Adding a semicolon at the end of an if clause is a common mistake. This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. DDC 2133 Programming II
11
Boolean Operators Operator Name ! not && and || or
DDC 2133 Programming II
12
Truth Table for Operator !
DDC 2133 Programming II
13
Truth Table for Operator &&
DDC 2133 Programming II
14
Truth Table for Operator ||
DDC 2133 Programming II
15
Examples Build a program that checks whether a number is divisible by 2 and 3, whether a number is divisible by 2 or 3, and whether a number is divisible by 2 or 3 but not both: DDC 2133 Programming II
16
#include <iostream> using namespace std; int main() {
int number; cout << "Enter an integer: "; cin >> number; if (number % 2 == 0 && number % 3 == 0) cout << number << " is divisible by 2 and 3." << endl; if (number % 2 == 0 || number % 3 == 0) cout << number << " is divisible by 2 or 3." << endl; if ((number % 2 == 0 || number % 3 == 0) && !(number % 2 == 0 && number % 3 == 0)) cout << number << " divisible by 2 or 3, but not both." << endl; return(0); } DDC 2133 Programming II
17
The if...else Statement if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; DDC 2133 Programming II
18
Examples Build a program that lets the user enter a year and checks whether it is a leap year. A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400. So you can use the following Boolean expression to check whether a year is a leap year: (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) DDC 2133 Programming II
19
#include <iostream> using namespace std; int main() {
cout << "Enter a year: "; int year; cin >> year; // Check if the year is a leap year bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); // Display the result in a message dialog box if (isLeapYear) cout << year << " is a leap year."; else cout << year << " is a not leap year."<<endl; return 0; } DDC 2133 Programming II
20
Multiple Alternative if Statements
DDC 2133 Programming II
21
Trace if-else statement
animation Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; DDC 2133 Programming II
22
Trace if-else statement
animation Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; DDC 2133 Programming II
23
Trace if-else statement
animation Trace if-else statement Suppose score is 70.0 The condition is true if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; DDC 2133 Programming II
24
Trace if-else statement
animation Trace if-else statement Suppose score is 70.0 grade is C if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; DDC 2133 Programming II
25
Trace if-else statement
animation Trace if-else statement Suppose score is 70.0 Exit the if statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; DDC 2133 Programming II
26
Note The else clause matches the most recent if clause in the same block. DDC 2133 Programming II
27
Nested if Statements if (i > k) { if (j > k) cout << "i and j are greater than k"; } else cout << "i is less than or equal to k"; DDC 2133 Programming II
28
Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) cout << "A"; } else cout << "B"; This statement prints B. DDC 2133 Programming II
29
TIP DDC 2133 Programming II
30
CAUTION DDC 2133 Programming II
31
Example: Computing Taxes
The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3.6. DDC 2133 Programming II
32
Example: Computing Taxes, cont.
#include <iostream> using namespace std; int main() { // Prompt the user to enter filing status cout << "Enter the filing status\n" << "(0-single filer, 1-married jointly,\n" << "2-married separately, 3-head of household): "; int status; cin >> status; // Prompt the user to enter taxable income cout << "Enter the taxable income: "; double income; cin >> income; // Compute tax double tax = 0; DDC 2133 Programming II
33
// Compute tax for single filers if (income <= 6000)
if (status == 0) { // Compute tax for single filers if (income <= 6000) tax = income * 0.10; else if (income <= 27950) tax = 6000 * (income ) * 0.15; else if (income <= 67700) tax = 6000 * ( ) * (income ) * 0.27; else if (income <= ) ( ) * (income ) * 0.30; else if (income <= ) ( ) * ( ) * (income ) * 0.35; else ( ) * (income ) * 0.386; } DDC 2133 Programming II
34
// Compute tax for married file jointly // Left as exercise }
else if (status == 1) { // Compute tax for married file jointly // Left as exercise } else if (status == 2) // Compute tax for married separately else if (status == 3) // Compute tax for head of household else cout << "Error: invalid status"; return (0); // Display the result cout << "Tax is " << static_cast<int>(tax * 100) / << endl; DDC 2133 Programming II
35
switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; case 2: compute taxes for married file separately; case 3: compute taxes for head of household; default: System.out.println("Errors: invalid status"); System.exit(0); } DDC 2133 Programming II
36
switch Statement Flow Chart
DDC 2133 Programming II
37
switch Statement Rules
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; … case valueN: statement(s)N; default: statement(s)-for-default; } The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. DDC 2133 Programming II
38
switch Statement Rules
The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; … case valueN: statement(s)N; default: statement(s)-for-default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. DDC 2133 Programming II
39
Trace switch statement
animation Trace switch statement Suppose ch is 'a': switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
40
Trace switch statement
animation Trace switch statement ch is 'a': switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
41
Trace switch statement
animation Trace switch statement Execute this line switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
42
Trace switch statement
animation Trace switch statement Execute this line switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
43
Trace switch statement
animation Trace switch statement Execute this line switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
44
Trace switch statement
animation Trace switch statement Execute next statement switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } Next statement; DDC 2133 Programming II
45
Trace switch statement
animation Trace switch statement Suppose ch is 'a': switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
46
Trace switch statement
animation Trace switch statement ch is 'a': switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
47
Trace switch statement
animation Trace switch statement Execute this line switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
48
Trace switch statement
animation Trace switch statement Execute this line switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; case 'c': cout << ch; } DDC 2133 Programming II
49
Trace switch statement
animation Trace switch statement Execute next statement switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; case 'c': cout << ch; } Next statement; DDC 2133 Programming II
50
Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to
y = (x > 0) ? 1 : -1; (booleanExpression) ? expression1 : expression2 DDC 2133 Programming II
51
cout << ((num % 2 == 0) ? "num is even" : "num is odd");
Conditional Operator cout << ((num % 2 == 0) ? "num is even" : "num is odd"); DDC 2133 Programming II
52
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2 DDC 2133 Programming II
53
Formatting Output DDC 2133 Programming II
54
Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?
DDC 2133 Programming II
55
Operator Precedence var++, var--
+, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator) DDC 2133 Programming II
56
Enumerated Types enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}; Once a type is defined, you can declare a variable of that type: Day day; The variable day can hold one of the values defined in the enumerated type. For example, the following statement assigns enumerated value MONDAY to variable day: day = MONDAY; DDC 2133 Programming II
57
Enumerated Types As with any other type, you can declare and initialize a variable in one statement: Day day = MONDAY; Furthermore, C++ allows you to declare an enumerated type and variable in one statement. For example, enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY} day = MONDAY; DDC 2133 Programming II
58
#include <iostream>
using namespace std; int main() { enum Day {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY} day; cout << "Enter a day (1 for Monday, 2 for Tuesday, etc): "; int dayNumber; cin >> dayNumber; switch (dayNumber) { case MONDAY: cout << "Play soccer" << endl; break; case TUESDAY: cout << "Piano lesson" << endl; case WEDNESDAY: cout << "Math team" << endl; default: cout << "Go home" << endl; } return 0; DDC 2133 Programming II
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.