03 Selections
03 Selections
Sections 3.13.16
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
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
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.
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
17
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
18
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
19
animation
Trace if-else statement
Suppose score is 70.0 grade is C
20
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
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.
35
Self-Study Example: Computing Taxes: Skeleton Code
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;
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
TestBooleanOperators Run
48
TestBooleanOperators.cpp
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
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.
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;
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.
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
62
animation
63
animation
64
animation
65
animation
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
70
Examples
• Equivalent statements:
• 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
73
Operator Precedence
74
Operator Associativity
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