Control Structures
A computer can proceed:
– In sequence
– Selectively (branch): making a choice
4. Control Structures – Repetitively (iteratively): looping
– By calling a function
Two most common control structures:
– Selection
– Repetition
1 2
Control Structures Relational Operators
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
– Require two operands (binary)
– Evaluate to true or false
3 4
3 4
Relational Operators and Simple Data
Relational Operators
Types
Relational operators can be used with all three simple
data types:
– 8 < 15 evaluates to true
– 6 != 6 evaluates to false
– 2.5 > 5.8 evaluates to false
– 5.9 <= 7.5 evaluates to true
5 6
5 6
Comparing Characters Relational Operators and the string Type
Expression of char values with relational operators Relational operators can be applied to strings
– ASCII character set – Strings are compared character by character, starting with
Logical (Boolean) expressions the first character
– Expressions such as 4 < 6 and 'R' > 'T’ – Comparison continues until either a mismatch is found or all
characters are found equal
– Returns an integer value of 1 if the logical expression
evaluates to true – If two strings of different lengths are compared and the
comparison is equal to the last character of the shorter
– Returns an integer value of 0 otherwise
string
The shorter string is less than the larger string
7 8
7 8
Relational Operators and the string Type Relational Operators and the string Type
Suppose we have the following declarations:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str4 = "Big";
9 10
9 10
Relational Operators and the string Type Relational Operators and the string Type
11 12
11 12
Logical (Boolean) Operators and Logical (Boolean) Operators and
Logical Expressions Logical Expressions
Logical (Boolean) operators: enable you to combine
logical expressions
13 14
13 14
Logical (Boolean) Operators and Logical (Boolean) Operators and
Logical Expressions Logical Expressions
15 16
15 16
Order of Precedence Order of Precedence
Relational and logical operators are evaluated from left
to right
– The associativity is left to right
Parentheses can override precedence
17 18
17 18
Order of Precedence Order of Precedence
19 20
19 20
The int Data Type and
Order of Precedence Logical (Boolean) Expressions
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
Can use the int data type to manipulate logical
(Boolean) expressions
21 22
21 22
The bool Data Type and
Selection: if and if...else
Logical (Boolean) Expressions
The data type bool has logical (Boolean) values true if and if...else statements can be used to create:
and false – One-way selection
bool, true, and false are reserved words – Two-way selection
The identifier true has the value 1
– Multiple selections
The identifier false has the value 0
23 24
23 24
One-Way Selection One-Way Selection
One-way selection syntax:
Statement is executed if the value of the expression is
true
Statement is bypassed if the value is false; program
goes to the next statement
Expression is called a decision maker
25 26
25 26
Two-Way Selection Two-Way Selection
Two-way selection syntax:
If expression is true, statement1 is executed;
otherwise, statement2 is executed
– statement1 and statement2 are any C++ statements
27 28
27 28
Compound (Block of) Statements Compound (Block of) Statements
Compound statement (block of statements): 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 functions like a single
statement
29 30
29 30
Multiple Selections: Nested if Multiple Selections: Nested if (cont’d.)
Nesting: one control statement is located within
another
An else is associated with the most recent if that
has not been paired with an else
31 32
31 32
Comparing if…else Statements with Comparing if…else Statements with if
a Series of if Statements Statements
33 34
33 34
Short-Circuit Evaluation Input Failure and the if Statement
Short-circuit evaluation: evaluation of a logical If input stream enters a fail state
expression stops as soon as the value of the expression – All subsequent input statements associated with that stream
is known are ignored
Example:
– Program continues to execute
– May produce erroneous results
(age >= 21) || ( x == 5) //Line 1
(grade == 'A') && (x >= 7) //Line 2 Can use if statements to check status of input stream
If stream enters the fail state, include instructions that
stop program execution
35 36
35 36
Confusion Between the Equality (==)
and Assignment (=) Operators
Conditional Operator (?:)
C++ allows you to use any expression that can be Conditional operator (?:)
evaluated to either true or false as an expression in – Ternary operator: takes 3 arguments
the if statement: Syntax for the conditional operator:
if (x = 5) expression1 ? expression2 : expression3
cout << "The value is five." << endl;
If expression1 is true, the result of the
conditional expression is expression2
– It is not a syntax error
Otherwise, the result is expression3
– It is a logical error
Example: max = (a >= b) ? a : b;
37 38
37 38
Program Style and Form (Revisited): Using Pseudocode to Develop, Test, and
Indentation Debug a Program
A properly indented program: Pseudocode, or just pseudo
– Helps you spot and fix errors quickly – Informal mixture of C++ and ordinary language
– Shows the natural grouping of statements – Helps you quickly develop the correct structure of the
Insert a blank line between statements that are program and avoid making common errors
naturally separate Use a wide range of values in a walk-through to
Two commonly used styles for placing braces
evaluate the program
– On a line by themselves
– Or left brace is placed after the expression, and the right
brace is on a line by itself
39 40
39 40
switch Structures
switch structure: alternate
to if-else
switch (integral) expression
is evaluated first
Value of the expression determines
which corresponding action is taken
Expression is sometimes
called the selector
41 42
41 42
switch Structures
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
switch, case, break, and default are
reserved words
43 44
43 44
Terminating a Program with the assert
Avoiding Bugs: Revisited
Function
To output results correctly Certain types of errors are very difficult to catch
– Consider whether the switch structure must include a – Example: division by zero
break statement after each cout statement
assert function: useful in stopping program
execution when certain elusive errors occur
45 46
45 46
The assert Function (cont’d.) The assert Function
Syntax: assert is useful for enforcing programming
constraints during program development
– expression is any logical expression After developing and testing a program, remove or
If expression evaluates to true, the next disable assert statements
statement executes The preprocessor directive #define NDEBUG must
If expression evaluates to false, the program be placed before the directive #include
terminates and indicates where in the program the <cassert> to disable the assert statement
error occurred
To use assert, include cassert header file
47 48
47 48
Why Is Repetition Needed? while Looping (Repetition) Structure
Repetition allows efficient use of variables • Syntax of the while statement:
Can input, add, and average multiple numbers using a
limited number of variables
For example, to add five numbers:
– Declare a variable for each number, input the numbers and • statement can be simple or compound
add the variables together
– Create a loop that reads a number into a variable and adds it
• expression acts as a decision maker and is usually a
to a variable that contains the sum of the numbers logical expression
• statement is called the body of the loop
• The parentheses are part of the syntax
49 50
49 50
while Looping (Repetition) Structure while Looping (Repetition) Structure
51 52
51 52
while Looping (Repetition) Structure while Looping (Repetition) Structure
i in Example 5-1 is called the loop control variable
(LCV)
Infinite loop: continues to execute endlessly
– Avoided by including statements in loop body that assure
the exit condition is eventually false
53 54
53 54
for Looping (Repetition) Structure for Looping (Repetition) Structure
• for loop: called a counted or indexed for loop
• Syntax of the for statement:
• The initial statement, loop condition, and
update statement are called for loop control
statements
55 56
55 56
for Looping (Repetition) Structure for Looping (Repetition) Structure
57 58
57 58
for Looping (Repetition) Structure
for Looping (Repetition) Structure
(cont’d.)
The following is a semantic error:
The following is a legal (but infinite) for loop:
for (;;)
cout << "Hello" << endl;
59 60
59 60
for Looping (Repetition) Structure do…while Looping (Repetition) Structure
• Syntax of a do...while loop:
• The statement executes first, and then the
expression is evaluated
– As long as expression is true, loop continues
• To avoid an infinite loop, body must contain a
statement that makes the expression false
61 62
61 62
do…while Looping (Repetition) Structure do…while Looping (Repetition) Structure
The statement can be simple or compound
Loop always iterates at least once
63 64
63 64
do…while Looping (Repetition) Structure Choosing the Right Looping Structure
All three loops have their place in C++
– If you know or can determine in advance the number of
repetitions needed, the for loop is the correct choice
– If you do not know and cannot determine in advance the
number of repetitions needed, and it could be zero, use a
while loop
– If you do not know and cannot determine in advance the
number of repetitions needed, and it is at least one, use a
do...while loop
65 66
65 66
break and continue Statements break and continue Statements
break and continue alter the flow of control continue is used in while, for, and do…while
break statement is used for two purposes: structures
– To exit early from a loop When executed in a loop
Can eliminate the use of certain (flag) variables – It skips remaining statements and proceeds with the next
– To skip the remainder of a switch structure iteration of the loop
After break executes, the program continues with the
first statement after the structure
67 68
67 68
Summary Summary
Control structures alter normal control flow Two selection structures: one-way selection and two-
Most common control structures are selection and way selection
repetition The expression in an if or if...else structure is
Relational operators: ==, <, <=, >, >=, != usually a logical expression
Logical expressions evaluate to 1 (true) or 0 (false) No stand-alone else statement in C++
Logical operators: ! (not), && (and), || (or)
– Every else has a related if
A sequence of statements enclosed between braces, {
and }, is called a compound statement or block of
statements
69 70
69 70
69 70
Summary Summary
Using assignment in place of the equality operator C++ has three looping (repetition) structures:
creates a semantic error – while, for, and do…while
switch structure handles multiway selection while, for, and do are reserved words
break statement ends switch statement while and for loops are called pretest loops
Use assert to terminate a program if certain do...while loop is called a posttest loop
conditions are not met while and for may not execute at all, but
do...while always executes at least once
71 72
71
71 72
Summary Summary
while: expression is the decision maker, and for loop: simplifies the writing of a counter-controlled
statement is the body of the loop while loop
A while loop can be: – Putting a semicolon at the end of the for loop is a semantic
– Counter-controlled error
– Sentinel-controlled Executing a break statement in the body of a loop
– EOF-controlled immediately terminates the loop
Executing a continue statement in the body of a loop
In the Windows console environment, the end-of-file
marker is entered using Ctrl+z skips to the next iteration
73 74
73 74