0% found this document useful (0 votes)
21 views76 pages

Control Structures in C ++ Chapter 4 - PPT Slides-1

C++ slides about control Structures

Uploaded by

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

Control Structures in C ++ Chapter 4 - PPT Slides-1

C++ slides about control Structures

Uploaded by

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

Chapter 4

Control Structures I (Selection)

C++ Programming: Program Design Including Data Structures, Eighth Edition

1
Objectives (1 of 2)

• In this chapter, you will:

• Learn about control structures

• Examine relational operators

• Discover how to use the selection control structures if, if…else

• Examine int and bool data types and logical (Boolean) expressions

• Examine logical operators

• Explore how to form and evaluate logical (Boolean) expressions

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 2
or otherwise on a password-protected website for classroom
Objectives (2 of 2)

• Learn how relational operators work with the string type

• Become aware of short-circuit evaluation

• Learn how the conditional operator, ?:, works

• Learn how to use pseudocode to develop, test, and debug a program

• Discover how to use a switch statement in a program

• Learn how to avoid bugs by avoiding partially understood concepts

• Learn how to use the assert function to terminate a program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 3
or otherwise on a password-protected website for classroom
Control Structures (1 of 2)

• So far, we have defined a program as a sequence of statements whose objective


is to accomplish some task and these statements were executed in order.

• However, a computer can proceed in multiple ways:

• In sequence

• Selectively (branch): making a choice

• Repetitively: looping

• By calling a function

• The two most common control structures are:

• Selection

• Repetition

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 4
or otherwise on a password-protected website for classroom
Control Structures (2 of 2)

FIGURE 4-1 Flow of execution

In selection, the program In repetition, the program repeats


executes particular statements particular statements a certain
depending on some condition(s). number of times based on some
condition(s).
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 5
or otherwise on a password-protected website for classroom
Selection: if AND if...else

• Execution of selection or repetition requires execution of a logical expression:

• An expression that evaluates to true or false is called a logical expression

• “8 is greater than 3” is true, hence

• 8 > 3 is a logical expression

• Conditional statements: only executed if certain conditions are met

• Condition: represented by a logical (Boolean) expression that evaluates to a


logical (Boolean) value of true or false

 Relational operators:

 Allow comparisons

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 6
or otherwise on a password-protected website for classroom
Relational Operators
TABLE 4-1 Relational Operators in C++

Operator Description
== equal to Remember: The
!= not equal to operators ==, !=,
<=, and >= are binary
< less than
operators (tokens) and
<= less than or equal to
there should be no
> greater than space within these
>= greater than or equal to operators.

• Each relational operator is a binary operator (requires two operands)


• Expressions using these operators always evaluate to true or false

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 7
or otherwise on a password-protected website for classroom
Relational Operators and Simple Data Types
• You can use the relational operators with all three simple data types

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 8
or otherwise on a password-protected website for classroom
Comparing Characters

• In an expression of char values using relational operators:

• The result depends on the machine’s collating sequence

- ASCII character set

‘R’ > ‘T’ is false ‘+’ < ‘*’ is false

‘A’ <= ‘a’ is true 8 < ‘5’ is true

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 9
or otherwise on a password-protected website for classroom
Logical (Boolean) expressions and data type bool

• Logical (Boolean) expressions:

• Include expressions such as 4 < 6 and 'R' > 'T’

• Return an integer value of 1 if the logical expression evaluates to true

• Return an integer value of 0 otherwise

• The returned (evaluated) value of a Boolean expression can be assigned to a


bool type identifier.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 10
or otherwise on a password-protected website for classroom
One-Way Selection (1 of 4)

If (Bolean expression)
• One-way selection syntax {
statement 1;
statement 2;

statement n;
• The statement is: }

• Executed if the value of the expression is true

• Bypassed if the value is false; program goes to the next statement

• The expression is also called a decision maker

• The statement following the expression is also called the action statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 11
or otherwise on a password-protected website for classroom
One-Way Selection (2 of 4)

FIGURE 4-2 One-way selection

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 12
or otherwise on a password-protected website for classroom
One-Way Selection (3 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 13
or otherwise on a password-protected website for classroom
One-Way Selection (4 of 4)

Practice Example Program 4-3

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 14
or otherwise on a password-protected website for classroom
Two-Way Selection (1 of 4)

• Two-way selection syntax

• If expression is true, statement1 is executed; otherwise,


statement2 is executed
• statement1 and statement2 are any C++ statements

• FIGURE 4-3 Two-way selection

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 15
or otherwise on a password-protected website for classroom
Two-Way Selection (2 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 16
or otherwise on a password-protected website for classroom
Two-Way Selection (3 of 4)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 17
or otherwise on a password-protected website for classroom
Two-Way Selection (4 of 4)

The above lines of code has a syntax error. Can you figure it out?

Check the output for all possible values of score.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 18
or otherwise on a password-protected website for classroom
int Data Type and Logical (Boolean) Expressions (1 of 2)

• Earlier versions of C++ did not provide built-in data types that had Boolean
values
• Logical expressions evaluate to either 1 or 0
• Logical expression value was stored in a variable of the data type int
• You can use the int data type to manipulate logical (Boolean) expressions
int legalAge;
int age = 25;
legalAge = 21;
If you regard legalAge as a logical variable, the value of legalAge assigned by this
statement is true.

The assignment statement: legalAge = (age >= 21);

assigns the value 1 to legalAge if the value of age is greater than or equal to 21.

The statement assigns the value 0 if the value of age is less than 21.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 19
or otherwise on a password-protected website for classroom
bool Data Type and Logical (Boolean) Expressions (2 of 2)

• The data type bool has logical (Boolean) values true and false
• bool, true, and false are reserved words
• The identifier true has the value 1
• The identifier false has the value 0
bool legalAge;
int age = 25;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 20
or otherwise on a password-protected website for classroom
Logical (Boolean) Operators and Logical Expressions (1 of 4)

• Logical (Boolean) operators enable you to combine two or more logical


expressions
TABLE 4-2 Logical (Boolean) Operators in C++
Operator Description
! not
&& and
|| or

Remember: The operators && and || are binary operators (tokens)


and there should be no space within these operators.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 21
or otherwise on a password-protected website for classroom
Logical (Boolean) Operators and Logical Expressions (2 of 4)

TABLE 4-3 The ! (Not) Operator

Expression !(Expression)
true (nonzero) false (0)
false (0) true (1)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 22
or otherwise on a password-protected website for classroom
Logical (Boolean) Operators and Logical Expressions (3 of 4)

TABLE 4-4 The && (And) Operator

Expression1 Expression2 Expression1 && Expression2


true (nonzero) true (nonzero) true (1)

true (nonzero) false (0) false (0)

false (0) true (nonzero) false (0)

false (0) false (0) false (0)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 23
or otherwise on a password-protected website for classroom
Logical (Boolean) Operators and Logical Expressions (4 of 4)

TABLE 4-5 The || (Or) Operator

Expression1 Expression2 Expression1 || Expression2


true (nonzero) true (nonzero) true (1)

true (nonzero) false (0) true (1)

false (0) true (nonzero) true (1)

false (0) false (0) false (0)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 24
or otherwise on a password-protected website for classroom
Order of Precedence (1 of 3)

• Relational and logical operators are also evaluated from left to right
• The associativity is left to right
• Parentheses can override precedence
TABLE 4-6 Precedence of Operators

Operators Precedence
!, +, - (unary operators) first
*, /, % second
+, - third
<, <=, >=, > fourth
==, != fifth
&& sixth
|| seventh
= (assignment operator) last

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 25
or otherwise on a password-protected website for classroom
Order of Precedence (2 of 3)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 26
or otherwise on a password-protected website for classroom
Order of Precedence (3 of 3)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 27
or otherwise on a password-protected website for classroom
Relational Operators and the string Type (1 of 5)

• Relational operators can be applied to variables of type string

• Strings are compared character by character, starting with the first character

• Comparison continues until either a mismatch is found or all characters are


found equal

• If two strings of different lengths are compared and the comparison is equal
to the last character of the shorter string

- The shorter string is less than the larger string

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 28
or otherwise on a password-protected website for classroom
Relational Operators and the string Type (2 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 29
or otherwise on a password-protected website for classroom
string str1 = "Hello";
string str2 = "Hi";
Relational Operators and the string Type (3 of 5) string str3 = "Air";
string str4 = "Bill";
string sr5 = "Big";

Expression Value/Explanation
str1 < str2 true
str1 = "Hello" and str2 = "Hi". The first character
of str1 and str2 are the same, but the second character
'e' of str1 is less than the second character 'i' of str2.
Therefore, str1 < str2 is true.
str1 > "Hen" false
str1 = "Hello". The first two characters of str1 and
"Hen" are the same, but the third character 'l' of str1
is less than the third character 'n' of "Hen". Therefore,
str1 > "Hen" is false.
str3 < "An" true
str3 = "Air". The first characters of str3 and "An" are
the same, but the second character 'i' of "Air" is less
than the second character 'n' of "An". Therefore, str3 <
"An" is true.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 30
or otherwise on a password-protected website for classroom
string str1 = "Hello";
Relational Operators and the string Type (4 of 5) string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";

Expression Value/Explanation
str1 == "hello" false
str1 = "Hello". The first character 'H' of str1 is less
than the first character 'h' of "hello" because the ASCII
value of 'H' is 72, and the ASCII value of 'h' is 104.
Therefore, str1 == "hello" is false.
str3 <= str4 true
str3 = "Air" and str4 = "Bill". The first character
'A' of str3 is less than the first character 'B' of str4.
Therefore, str3 <= str4 is true.
str2 > str4 true
str2 = "Hi" and str4 = "Bill". The first character 'H'
of str2 is greater than the first character 'B' of str4.
Therefore, str2 > str4 is true.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 31
or otherwise on a password-protected website for classroom
string str1 = "Hello";
Relational Operators and the string Type (5 of 5) string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";

Expression Value/Explanation
str4 >= "Billy" false
str4 = "Bill". It has four characters and "Billy" has
five characters. Therefore, str4 is the shorter string. All
four characters of str4 are the same as the corresponding
first four characters of "Billy", and "Billy" is the larger
string. Therefore, str4 >= "Billy" is false.
str5 <= "Bigger" true
str5 = "Big". It has three characters and "Bigger" has
six characters. Therefore, str5 is the shorter string. All
three characters of str5 are the same as the corresponding
first three characters of "Bigger", and "Bigger" is the
larger string. Therefore, str5 <= "Bigger" is true.

Note: If two strings of different lengths are compared and the character-by-
character
comparison is equal until it reaches the last character of the shorter string, the
shorter string is evaluated as less than the larger string.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 32
or otherwise on a password-protected website for classroom
Compound (Block of) Statements

• So far, the syntax of if and if. . .else structures have been explained to control
only one statement at a time. However, we can also execute multiple statements
in order as a consequence of evaluation results of if and if. . .else expressions.
• A compound statement (block of statements) has this form:
if (age > 18)
{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}
• A compound statement consists of one or more statements enclosed in curly
braces, { and }.
• A compound statement functions like a single statement
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 33
or otherwise on a password-protected website for classroom
Multiple Selections: Nested if (1 of 5)

• When one control statement is located within another, it is said to be nested

• How do you know which else is paired with which if?

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 34
or otherwise on a password-protected website for classroom
Multiple Selections: Nested if (2 of 5)

• Recall: in C++, there is no stand-alone else statement.


• Every else must be paired with an if.

• Pairing an else with an if: In a nested if statement, C++ associates an else with
the most recent incomplete if—that is, the most recent if that has not been
paired with an else.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 35
or otherwise on a password-protected website for classroom
Multiple Selections: Nested if (3 of 5)

The else in Line 3 is paired with the if in Line 1.


The else in Line 6 is paired with the if in Line 4.
The else in Line 9 is paired with the if in Line 7.

This means that the block for each else extends from the else all the way to line
10.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 36
or otherwise on a password-protected website for classroom
Multiple Selections: Nested if (4 of 5)

The else in Line 4 is paired with the if in Line 2, and the else in Line 6
is paired with the if in Line 1.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 37
or otherwise on a password-protected website for classroom
Multiple Selections: Nested if (5 of 5)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 38
or otherwise on a password-protected website for classroom
Comparing if…else Statements with a Series of if Statements (1 of 2)

a. If a statement associated with


if executes; the rest of the
structure and statements are
skipped.
• If more than one condition is
true, only the statements
associated with the first true
condition will be executed.
b. The computer has to evaluate
the expression in each if
statement. The program code
(b) executes more slowly than
the program code (a).
• If more than one condition
evaluates to true in (b), then
the statements associated
with each true condition will
execute.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 39
or otherwise on a password-protected website for classroom
Short-Circuit Evaluation

• The computer evaluates the logical expression from left to right.


• Short-circuit evaluation: evaluation of a logical expression stops As soon as the
final value of the entire logical expression is known

Suppose:
age = 25;
grade = ‘B’;
• In his case, due to short-circuit evaluation, the computer will not evaluate the
expression (x == 5) because the expression (age >= 21) will be evaluated
first as true .
• Because ('B' == 'A') is false and the logical operator used in the expression is
&&, the expression evaluates to false. The computer does not evaluate (x >= 7).

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 40
or otherwise on a password-protected website for classroom
Comparing Floating-Point Numbers for Equality: A Precaution

• Comparison of floating-point numbers for equality may not behave as you would expect

• Example:

1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0 evaluates to false

Why?

3.0/7.0 + 2.0/7.0 + 2.0/7.0 = 0.99999999999999989

• A solution is checking for a tolerance value

• Example: if fabs(x – y) < 0.000001

- fabs is defined inside the header file ‘cmath’

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 41
or otherwise on a password-protected website for classroom
Associativity of Relational Operators: A Precaution (1 of 3)

#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter an integer: ";
cin >> num;
cout << endl;
if (0 <= num <= 10)
cout << num << " is within 0 and 10." << endl;
else
cout << num << " is not within 0 and 10.“
<< endl;
return 0;
}
• What is Wrong with my if statement?
• The if statement is a legal C++
expression.
• Means no Syntax error.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 42
or otherwise on a password-protected website for classroom
Associativity of Relational Operators: A Precaution (2 of 3)

Let us evaluate this expression for certain values of


num.
• num = 5
0 <= num <= 10 = 0 <= 5 <= 10
= (0 <= 5) <= 10 (Because relational operators
are evaluated from left to right)
= 1 <= 10 (Because 0 <= 5 is true,
0 <= 5 evaluates to 1)
= 1 (true)

• num = 20
0 <= num <= 10 = 0 <= 20 <= 10
= (0 <= 20) <= 10 (Because relational operators
are evaluated from left to right)
= 1 <= 10 (Because 0 <= 20 is true,
0 <= 20 evaluates to 1)
= 1 (true)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 43
or otherwise on a password-protected website for classroom
Associativity of Relational Operators: A Precaution (3 of 3)

• The expression if (0 <= num <= 10) will always evaluate out to
be true no matter what the vale of the variable num to be.

• This is due to the fact that the expression 0 <= num evaluates to either 0 or

1, and either of the final expressions 0 <= 10 or 1 <= 10 will always be


true.

• So, what is/are the correct way(s) ? Either of the following will do the
GOOD!

1. 0 <= num && num <= 10

2. (0 <= num) && (num <= 10)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 44
or otherwise on a password-protected website for classroom
Avoiding Bugs by Avoiding Partially Understood Concepts and
Techniques (1 of 3)
• Must use concepts and techniques correctly
• Otherwise, solution will be either incorrect or deficient
• If you do not understand a concept or technique completely
• Do not use it
• Save yourself an enormous amount of debugging time

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 45
or otherwise on a password-protected website for classroom
Avoiding Bugs by Avoiding Partially Understood Concepts and
Techniques (2 of 3)
// GPA program with bugs.
#include <iostream> //Line 1
using namespace std; //Line 2
int main() //Line 3
{ //Line 4
double gpa; //Line 5
cout << "Enter the GPA: "; //Line 6
cin >> gpa; //Line 7
cout << endl; //Line 8
if (gpa >= 2.0) //Line 9
if (gpa >= 3.9) //Line 10
cout << "Dean\'s Honor List." << endl; //Line 11
else //Line 12
cout << "The GPA is below the graduation "
<< "requirement. \nSee your "
<< "academic advisor." << endl; //Line 13
return 0; //Line 14
} //Line 15

Following the rule of pairing, the else in Line 12 is paired with the
if in Line 10. Here, improper use of indentation is creating a
wrong impression that the else in Line 12 is paired with the if in
Line 9. 46
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service
or otherwise on a password-protected website for classroom
Avoiding Bugs by Avoiding Partially Understood Concepts and
Techniques (3 of 3)

// Correct GPA program.


#include <iostream> //Line 1
using namespace std; //Line 2 General rule:
int main() //Line 3 You cannot look
{ //Line 4 inside of a block
double gpa; //Line 5
(that is, inside
cout << "Enter the GPA: "; //Line 6
cin >> gpa; //Line 7 the braces) to
cout << endl; //Line 8 pair an else
if (gpa >= 2.0) //Line 9 with an if.
{ //Line 10
if (gpa >= 3.9) //Line 11
cout << "Dean\'s Honor List." << endl; //Line 12
} //Line 13
else //Line 14
cout << "The GPA is below the graduation "
<< "requirement. \nSee your "
<< "academic advisor." << endl; //Line 15
return 0; //Line 16
} //Line 17

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 47
or otherwise on a password-protected website for classroom
Input Failure and the if statement (1 of 6)

• Things can go wrong during execution

• If input data does not match corresponding variables, program may run into
problems

• Trying to read a ch into an int or double variable will result in an input


failure

• In addition to reading invalid data, other events can also cause an input stream
to enter the fail state.

• Attempting to open an input file that does not exist

• Attempting to read beyond the end of an input file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 48
or otherwise on a password-protected website for classroom
Input Failure and the if statement (2 of 6)

• If an input stream enters a fail state:

• All subsequent input statements associated with that stream are ignored

• Program continues to execute

• The code may produce erroneous results

• Necessary Precaution: Use if statements to check status of input stream

• If the input stream enters the fail state, adopt one the following strategies

• include instructions that restore the input stream to its normal working again and re-
enter the input(s)

• include instructions that stop program execution if you don’t want to or can’t re-enter
the input(s)

- This is specially the case when input data file doesn’t exist

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 49
or otherwise on a password-protected website for classroom
Input Failure and the if statement (3 of 6)

• We can use the if statement to check input failure and take appropriate actions.

• The input failure can be handled by checking the stream variable as the expression of
the if statement.

if(!cin) if(!infile)

Action_Statement(s); Action_Statement(s);

Use compound statement structure if you


want to execute more than one statements.

• An input failure sets the stream variable to false, otherwise it is set to true.

• Hence, the above conditional expression in the if statement will evaluate to true in
case of input failure.

• We can use the clear and ignore functions to reset the input stream status.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 50
or otherwise on a password-protected website for classroom
Input Failure and the if statement (4 of 6)

• The clear function restores input stream to a working state

istreamVar.clear();
• ignore function

• Discards a portion of the input

• Ignores previously buffered data in input stream

istreamVar.ignore();

Calling the ignore function as above will ignore any previous input and prepares
the input stream to accept the inputs afresh (starting again from the first input).

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 51
or otherwise on a password-protected website for classroom
Input Failure and the if statement (5 of 6)

• Examples
if(!cin) if(!infile)
{ {
cin.(clear); infile.(clear);
cin.ignore(); infile.ignore();
} }

ifstream infile;
infile.open("inputdat.dat"); //open file inputdat.dat
if(!infile)
{
cout << “Can’t open the input file. ”
<< “The program terminates.” << endl;
return 1;
}

• Practice Example: Ch4_AverageTestScore

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 52
or otherwise on a password-protected website for classroom
Input Failure and the if statement (6 of 6)

int main()
{
int x;
double f;
cout << “Enter the value of x: “ << endl;
cin >> x;
// if invalid value for x is entered, e.g. a char is entered
if(!cin)
{
cout << "Input failed." << endl;
cin.clear();
cin.ignore();
cout << "Enter x again: ";
cin >> x;
}
cin >> f;
cout << x << " “ << f << endl;
return 0;
}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 53
or otherwise on a password-protected website for classroom
Confusion Between the Equality (==) and Assignment (=) Operators

• C++ allows you to use any expression that can be evaluated to either true or false as
an expression in the if statement
if (x = 5)
cout << "The value is five." << endl;
In general, the expression x = a, where a is a The expression x = 0, will
nonzero integer, will always evaluate to true. always evaluate to false.
• The appearance of = in place of == resembles a silent killer
• It is not a syntax error : something that compiler will catch and report

• It is a logical error : an error that is not reported at compile-time, but the program output is
incorrect due to this error

• Warning: This kind of error will also set the value of x to a or 0

• Similarly, suppose x, y, and z are int variables.

• The statement x == y + z; will just compare the values on both sides of the logical
operator == and will not update the vale of x

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 54
or otherwise on a password-protected website for classroom
Conditional Operator (?:)

• Conditional operator (?:)


• Ternary operator: takes three arguments
• Syntax for the conditional operator
expression1 ? expression2 : expression3
• If expression1 is true, the result of the conditional expression is
expression2
• Otherwise, the result is expression3
• Example: To find maximum of the two values
max = (a >= b) ? a : b;
• Another Example: Age is an integer variable
age > 60 ? cout << “hello old citizen” : cout << “hello
young man”;

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 55
or otherwise on a password-protected website for classroom
Conditional Operator (?:)

 The conditional operator can also be used with the cout statement as below.
cout << (a >= b) ? a : b;
or
cout << (a >= b) ? “A” : “B” << “ is larger!”;

 In the second example above, the result of the conditional expression is either
“A” or “B”, so either one of them will be printed.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 56
or otherwise on a password-protected website for classroom
Nested Conditional Operator (?:)

 The conditional operator can also be “nested” just like other selection
statements. See example below:
• Yet another example (nested if):
age > 60 ? cout << “hello old citizen”; : (age > 40 ? cout
<< “hello gentleman” : cout << “hello young man”);

 Assume grade and gpa already declared:


grade == ‘a’ ? gpa = 4.0 : grade == ‘b’ ? gpa = 3.0 :
grade == ‘c’ ? gpa = 2.0 : gpa = 0.0;

 Each differently colored statement above starts a new conditional operator.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 57
or otherwise on a password-protected website for classroom
Program Style and Form (Revisited): Indentation

• A properly indented program:


• Helps you spot and fix errors quickly

• Shows the natural grouping of statements

• Insert a blank line between statements that are naturally separate

• Two commonly used styles for placing braces


• On a line by themselves
• Or left brace is placed after the expression, and the right brace is on a line by
itself

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 58
or otherwise on a password-protected website for classroom
Using Pseudocode to Develop, Test, and Debug a Program

• Pseudocode (or just pseudo) is an informal mixture of C++ and ordinary


language
• Helps you quickly develop the correct structure of the program and avoid making
common errors

• Use a wide range of values in a walk-through to refine the final program

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 59
or otherwise on a password-protected website for classroom
switch Structures (1 of 5)

• If or if…else structures, use logical expressions to decide about certain actions

• A logical expressions can evaluate to the only Boolean true/false values

• One can also use a bool type identifier in place of logical expression

• However, due to Boolean nature of the expressions or identifier, one can only decide
among two alternative actions

• switch structure is an alternate to if … else which also allows use of more general
integral expressions in addition to the use of logical expressions

• An integral expression can evaluate to many integer values. It can also simply be an
identifier of type int

• Therefore, switch structure allows to choose from among many alternatives


depending upon the integer value

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 60
or otherwise on a password-protected website for classroom
switch Structures (2 of 6)

• switch (integral/logical) expression is


switch (int expression)
evaluated first {
case value1:
• Value of the expression determines which statements1
break;
corresponding action is taken case value2:
statements2
• Expression is sometimes called the selector break;
.
switch (logical expression) .
{ .
case true: case valuen:
statements1 statementsn
break; break;
case false: default:
statements2 statements
} }

switch, case, break, and Shading indicates an optional


default are reserved words. part of the Syntax.
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 61
or otherwise on a password-protected website for classroom
switch Structures (2 of 6)

FIGURE 4-4 switch statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 62
or otherwise on a password-protected website for classroom
switch Structures (3 of 6)

• A particular case value should appear only once

• One or more statements may follow a case label

• Braces are not needed to turn multiple statements into a single compound statement

• When a case value is matched, all statements after it execute until a break is
encountered

• The break statement may or may not appear after each statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 63
or otherwise on a password-protected website for classroom
switch Structures (4 of 6)

• switch : The Fall-through effect

 Missing a break statement in a case inside the switch statement may result
in the so-called fall through effect.

 All the subsequent cases will run (no matter the case is matched or not),
unless another break statement appears.

 Example on Next slide

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 64
or otherwise on a password-protected website for classroom
switch Structures (5 of 6)

 A break statement missing in case


‘B’ and ‘C’.
 If grade contains ‘B’, then case ‘B’
will be matched.
 But, as there are no break
statement after case ‘B’, so case ‘C’
and case ‘D’ will also run. The
break after case ‘D’ will then end
the switch statement.

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 65
or otherwise on a password-protected website for classroom
switch Structures (6 of 6)

• Example: Covert the following switch statement into an equivalent nested if statement
such that the program output remains the same. Assume alpha is an integer variable already
declared. (HINT: Be careful of the fall-through effect while converting cases with the missing
break statements.) if(alpha == 1 || alpha == 2)
alpha = alpha + 2;
else
{
if (alpha == 4)
{
alpha++;
alpha = 2 * alpha;
alpha = alpha + 5;
}
else if(alpha == 5)
{
alpha = 2 * alpha;
alpha = alpha + 5;
}
else if(alpha == 6)
alpha = alpha + 5;
else
alpha--;
}

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 66
or otherwise on a password-protected website for classroom
Avoiding Bugs: Revisited

• To output results correctly


• Consider whether the switch structure must include a break statement after each
cout statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 67
or otherwise on a password-protected website for classroom
Terminating a Program with the assert Function

• Certain types of errors are very difficult to catch


• Example: division by zero
• The assert function is useful in stopping program execution when certain
elusive errors occur
• Syntax

expression is any logical expression

• If expression evaluates to true, the next statement executes


• If expression evaluates to false, the program terminates and indicates
where in the program the error occurred
• To use assert, include cassert header file

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 68
or otherwise on a password-protected website for classroom
The assert Function (2 of 2)

• assert is useful for enforcing programming constraints during program


development
• After developing and testing a program, remove or disable assert statements
• The preprocessor directive #define NDEBUG must be placed before the
directive #include <cassert> to disable the assert statement

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 69
or otherwise on a password-protected website for classroom
The assert Function (2 of 2)

int numerator;
int denominator;
int quotient;
assert(denominator);
quotient = numerator / denominator;

Now, if denominator is 0, the assert statement halts the of the program with an
error message similar to the following:

Assertion failed: denominator, file c:\temp\assert

function\assertfunction.cpp, line 20

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 70
or otherwise on a password-protected website for classroom
Quick Review (1 of 3)

• Control structures alter normal control flow


• Most common control structures are selection and repetition
• Relational operators: ==, <, <=, >, >=, !=
• Logical expressions evaluate to 1 (true) or 0 (false)
• Logical operators: ! (not), && (and), || (or)

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 71
or otherwise on a password-protected website for classroom
Quick Review (2 of 3)

• Two selection structures are one-way selection and two-way selection


• The expression in an if or if...else structure is usually a logical
expression
• No stand-alone else statement exists in C++
• Every else has a related if
• A sequence of statements enclosed between braces, { and }, is called a
compound statement or a block of statements

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 72
or otherwise on a password-protected website for classroom
Quick Review (3 of 3)

• Using assignment in place of the equality operator creates a semantic error


• The execution of a switch structure handles multiway selection
• The execution of a break statement ends a switch statement
• Use assert to terminate a program if certain conditions are not met

© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 73
or otherwise on a password-protected website for classroom
Home Assignment

• Read, understand and practice all the examples of Chapter 4

• Make flowcharts for algorithms used in the programming examples

1. Cable Company Billing

• Prepare the Exercise Questions (1-34) given at the end of Chapter 4

• Complete the Programming Exercises: Exercises 1, 2, 4, 5, 6 , 7 , 9, 14, 18, 20


• Design an algorithm and write a program to implement the following.

• A student spends a majority of his weekend playing and watching sports, thereby tiring
him out and leading him to oversleep and often miss his Monday 8 AM math class.
Suppose that the tuition per semester is $25,000 and the average semester consists of
15 units. If the math class meets three days a week, one hour each day for 15 weeks,
and is a four-unit course, how much does each hour of math class cost the student?
Design an algorithm that computes the cost of each math class.

74
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 74
or otherwise on a password-protected website for classroom
Home Assignment

• Read, understand and practice all the examples of Chapter 4

• Make flowcharts for algorithms used in the programming examples

1. Cable Company Billing

• Prepare the Exercise Questions (1-34) given at the end of Chapter 4

• Complete the Programming Exercises: Exercises 1, 2, 4, 5, 6 , 7 , 9, 14, 18, 20


• Design an algorithm and write a program to implement the following.

• A student spends a majority of his weekend playing and watching sports, thereby tiring
him out and leading him to oversleep and often miss his Monday 8 AM math class.
Suppose that the tuition per semester is $25,000 and the average semester consists of
15 units. If the math class meets three days a week, one hour each day for 15 weeks,
and is a four-unit course, how much does each hour of math class cost the student?
Design an algorithm that computes the cost of each math class.

75
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 75
or otherwise on a password-protected website for classroom
Home Assignment
• Design an algorithm and write a program to implement the following.

• An ATM allows a customer to withdraw a maximum of $500 per day. If a customer


withdraws more than $300, the service charge is 4% of the amount over $300. If the
customer does not have sufficient money in the account, the ATM informs the customer
about the insufficient fund and gives the option to withdraw the money for a service
charge of $25.00. If there is no money in the or if the account balance is negative, the
ATM does not allow the customer to withdraw any money. If the amount to be withdrawn
is greater than $500, the ATM informs the customer about the maximum amount that can
be withdrawn. Write an algorithm that allows the customer to enter the amount to be
withdrawn. The algorithm then checks the total amount in the account, dispenses the
money to the customer, and debits the account by the amount withdrawn and the service
charges, if any.

• Assume that the account balance is stored in the file ATM_Data.txt. Your program should
output account balance before and after withdrawal and service charges. Also save the
account balance after withdrawal in the file ATM_Output.txt.
76
© 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service 76
or otherwise on a password-protected website for classroom

You might also like