0% found this document useful (0 votes)
9 views78 pages

03 Selections

Uploaded by

yazan.alsaudi99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views78 pages

03 Selections

Uploaded by

yazan.alsaudi99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Chapter 3: Selections

Sections 3.13.16

Textbooks: Y. Daniel Liang, Introduction to Programming with C++, 3rd Edition


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.

These slides were adapted by Prof. Gheith Abandah from the Computer Engineering Department of the University
of Jordan for the Course: Computer Skills for Engineers (0907101)
Updated by Dr. Ashraf Suyyagh (Summer 2021)
1
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
2
Introduction

If you assigned a negative value for radius in


Listing 2.1, ComputeArea.cpp, the program would
print an invalid result. If the radius is negative, you
don't want the program to compute the area. How
can you deal with this situation?

3
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
4
The bool Type and Operators
Often in a program you need to compare two values,
such as whether i is greater than j. C++ provides six
relational operators (also known as comparison
operators):

5
The bool Type and Operators
A variable that holds a Boolean value is known as a
Boolean variable, which holds true or false.
bool lightsOn = true;
cout << lightsOn; // Displays 1
cout << (4 < 5); // Displays 1
cout << (4 > 5); // Displays 0

Any nonzero value evaluates to true and zero value


evaluates to false.
bool b1 = -1.5; // ≡ bool b1 = true;
bool b2 = 0; // ≡ bool b2 = false;
bool b3 = 1.5; // ≡ bool b3 = true;
6
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
7
One-way if Statements
if (booleanExpression)
{
statement(s);
}

if (radius >= 0)
{
area = radius * radius * PI;
cout << "The area for the circle of " <<
" radius " << radius << " is " << area;
}
8
Notes
• The boolean-expression must be enclosed in
parentheses.

• The braces can be omitted if they enclose a single


statement.

9
Simple if Demo
A program that prompts the user to enter an integer. If the number
is a multiple of 5, displays HiFive. If the number is even, displays
HiEven.

SimpleIfDemo Run

10
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
11
Two-Way if-else Statement
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}

12
Examples

13
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
14
Nested if Statements
You can nest multiple 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";

15
Multiple Alternative if Statements

16
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

17
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

18
animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

19
animation
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

20
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


cout << "Grade is A";
else if (score >= 80.0)
cout << "Grade is B";
else if (score >= 70.0)
cout << "Grade is C";
else if (score >= 60.0)
cout << "Grade is D";
else
cout << "Grade is F";

21
Note
The else clause matches the most recent if clause in
the same block.

22
Note, cont.
Nothing is printed from the Statement (a) above. To force
the else clause to match the first if clause, you must
add a pair of braces:

int i = 1, j = 2, k = 3;
if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";
This statement prints B. 23
TIP

24
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
25
Common Errors
1: Forgetting Necessary Braces

26
Common Errors
2: Wrong Semicolon at the if Line

27
Common Errors
3: Mistakenly Using = for ==

if (count = 1)
cout << "count is zero" << endl;
else
cout << "count is not zero" << endl;

28
Common Errors
4: Redundant Testing of Boolean Values

29
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
30
Case Study: Body Mass Index
The Body Mass Index (BMI) is a measure of health on
weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters (). The interpretation of BMI for people 16 years or
older is as follows:

ComputeBMI Run
31
Case Study: Body Mass Index

32
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
33
Self-Study Example: Computing Taxes
The Jordan income tax is calculated based on the filing status and taxable
income. In this simplified example, there are three filing statuses: single
filers, married couple filing jointly, and business filing.

The taxable income is calculated as follows:


• Single filers taxable income = total income from all sources – 9000 JDs
exemption
• Married filers taxable income = total income from all sources – 18000
JDs exemption – 1000JDs for each child up to three children
The businesses are divided into three categories:
1. (Group 1) Banking sector
2. (Group 2) Insurance, communication, mining, power generation
companies.
SELF-STUDY Examples are not explained in
3. (Group 3) Others class because they are very long examples.
Students are advised to watch the video
recorded and provided by the professor 34
Self-Study Example: Computing Taxes
• The tax rates for 2020 and beyond are shown
below:

35
Self-Study Example: Computing Taxes: Skeleton Code

if (income > 0){


if (status == 0)
{
// Compute tax for single filers
}
else if (status == 1)
{
// Compute tax for married file jointly
}
else if (status == 2)
{
// Compute tax for business
}
}

36
Self-Study Example: Computing Taxes: First
Case Details
if (status == 0)
{
double taxableIncome = income – 9000;
// Compute tax for single filers
if (taxableIncome <= 5000 && taxableIncome >= 0)
tax = taxableIncome * 0.05;
else if (taxableIncome <= 10000)
tax = 5000 * 0.05 + (taxableIncome - 5000) * 0.10;
else if (taxableIncome <= 15000)
tax = (5000 * 0.05) + (5000 * 0.10) +
(taxableIncome - 10000) * 0.15;
else if (taxableIncome <= 20000)

}
else if (status == 1)

37
Self-Study Example: Computing Taxes:
Second Case Details
if (status == 1)
{
int noChild = min(3, children)
double taxableIncome = income – 18000 – 1000*noChild;
// Compute tax for married filing jointly
if (taxableIncome <= 5000 && taxableIncome >= 0)
tax = taxableIncome * 0.05;
else if (taxableIncome <= 10000)
tax = 5000 * 0.05 + (taxableIncome - 5000) * 0.10;
else if (taxableIncome <= 15000)
tax = (5000 * 0.05) + (5000 * 0.10) +
(taxableIncome - 10000) * 0.15;
else if (taxableIncome <= 20000)

}
else if (status == 2)

38
Self-Study Example: Computing Taxes:
Third Case Details
if (status == 2)
{
//Divide into three business groups
if (group == 1)
tax = profit * 0.35;
else if (group == 2)
tax = profit * 0.24;
else if (group == 3)
tax = profit * 0.20;
}

39
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
40
Generating Random Numbers
• You can use the rand() function to obtain a
random integer.
• This function returns a random integer between
0 and RAND_MAX (32,767 in Visual C++).
• To start with a different seed at each execution,
use
srand(time(0));
• To obtain a random integer between 0 and 9, use
rand() % 10
41
Example: A Simple Math Learning Tool
• This example creates a program for a first grader to
practice subtractions.
• The program randomly generates two single-digit
integers number1 and number2 with number1
>= number2 and displays a question such as
“What is 9 – 2?” to the student.
• After the student types the answer, the program
displays a message to indicate whether the answer is
correct.

SubtractionQuiz Run

42
SubtractQuiz.cpp 1/2
#include <iostream>
#include <ctime> // for time function
#include <cstdlib> // for rand and srand functions
using namespace std;

int main()
{
// 1. Generate two random single-digit integers
srand(time(0));
int number1 = rand() % 10;
int number2 = rand() % 10;

// 2. If number1 < number2, swap number1 with number2


if (number1 < number2)
{
int temp = number1;
number1 = number2;
number2 = temp;
} 43
SubtractQuiz.cpp 2/2
// 3. Ask the student “what is number1 – number2?”
cout << "What is " << number1 << " - " << number2 << "? ";
int answer;
cin >> answer;

// 4. Grade the answer and display the result


if (number1 - number2 == answer)
cout << "You are correct!";
else
cout << "Your answer is wrong.\n“
<< number1 << " - “ << number2
<< " should be " << (number1 - number2) << endl;

return 0;
} 44
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
45
Logical Operators
• The logical operators !, &&, and || can be used to
create a compound Boolean expression.

46
47
Examples

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:

TestBooleanOperators Run

48
TestBooleanOperators.cpp
#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);
49
}
Short-Circuit Operator
• When evaluating p1 && p2, C++ first evaluates p1
and then evaluates p2 if p1 is true; if p1 is false,
it does not evaluate p2.
• When evaluating p1 || p2, C++ first evaluates p1
and then evaluates p2 if p1 is false; if p1 is true,
it does not evaluate p2.
• Therefore, && is referred to as the conditional or short-
circuit AND operator, and || is referred to as the
conditional or short-circuit OR operator.

50
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
51
Case Study: Determining Leap
Year
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)
LeapYear Run

52
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
53
Case Study: Lottery
Randomly generates a lottery of a two-digit number,
prompts the user to enter a two-digit number, and
determines whether the user wins according to the
following rule:
• If the user input matches the lottery in exact order,
the award is $10,000.
• If the user input matches the lottery, the award is
$3,000.
• If one digit in the user input matches a digit in the
lottery, the award is $1,000.
Lottery Run
Lottery.cpp 1/2
#include <iostream>
#include <ctime> // for time function
#include <cstdlib> // for rand and srand functions
using namespace std;

int main()
{
// Generate a lottery
srand(time(0));
int lottery = rand() % 100;

// Prompt the user to enter a guess


cout << "Enter your lottery pick (two digits): ";
int guess;
cin >> guess;

55
Lottery.cpp 1/2
// Check the guess
if (guess == lottery)
cout << "Exact match: you win $10,000" << endl;
else if (guess % 10 == lottery / 10
&& guess / 10 == lottery % 10)
cout << "Match all digits: you win $3,000" << endl;
else if (guess % 10 == lottery / 10
|| guess % 10 == lottery % 10
|| guess / 10 == lottery / 10
|| guess / 10 == lottery % 10)
cout << "Match one digit: you win $1,000" << endl;
else
cout << "Sorry, no match" << endl;

return 0;
} 56
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
57
switch Statements
switch (status)
{
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: cout << "Errors: invalid status" << endl;
}

58
switch Statement Flow Chart

59
switch Statement Rules
The switch-expression
must yield a integral value
and must always be
enclosed in parentheses.

The case values must be


integral constant expressions,
meaning that they cannot
contain variables in the
expression, such as 1 + x.

60
switch Statement Rules
The break is optional, but it
should be used at the end of
each case in order to
terminate the remainder of
the switch statement.

The default
case, which is optional,
can be used to perform When the value in a case statement matches the
actions when none of value of the switch-expression, the statements
the specified cases is starting from this case are executed until either
executed. a break statement or the end of the switch
statement is reached.
61
animation

Trace switch statement


Suppose day is 3:

62
animation

Trace switch statement


Execute case 3

63
animation

Trace switch statement


Fall to case 4

64
animation

Trace switch statement


Fall to case 5 then break

65
animation

Trace switch statement


Execute what is next

66
Example: Chinese Zodiac
A program that prompts the user to enter a year and
displays the animal for the year.

ChineseZodiac Run

67
ChineseZodiac.cpp

68
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
69
Conditional Expressions
A conditional expression evaluates an expression based
on a condition.

Syntax:
(booleanExpression) ? expression1 : expression2

The result of this conditional expression is expression1 if


boolean-expression is true; otherwise, the result is
expression2.

70
Examples
• Equivalent statements:

• Finding the max:

• Odd of even:

71
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
72
Operator Precedence and Associativity

Operator precedence and associativity determine the


order in which operators are evaluated.

How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?


false?

3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 – 3 > 5)?


false?

73
Operator Precedence

74
Operator Associativity

• All binary operators except assignment


operators are left associative.
• Assignment operators are right associative.

75
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
76
Debugging
• Debugging is the process of finding and fixing
errors in a program.
• Visual Studio supports debugging:
– Executing a single statement at a time
– Tracing into or stepping over a function
– Setting breakpoints
– Displaying variables
– Displaying call stacks
– Modifying variables
• Show demo on Visual Studio 2019.
77
Outline
• Introduction • Generating Random
• The bool Data Type Numbers
• if Statements • Logical Operators
• Two-Way if-else Statements • Case Study: Determining
• Nested if and Multi-Way if- Leap Year
else Statements • Case Study: Lottery
• Common Errors and Pitfalls • switch Statements
• Case Study: Computing • Conditional Expressions
Body Mass Index • Operator Precedence and
• Case Study: Computing Associativity
Taxes • Debugging
78

You might also like