Module 4: Control structures I (Selection)
Lecture : Selection in C++ program
Control structures
A computer can process a program in one of the following ways:
1) In sequence;
2) Selectively
By making a choice, which is also called a branch
3) Repetitively
By executing a statement over and over, using a structure
called a loop
4) By calling a function
Control structures
In a sequential program
The computer starts at the beginning and follows the
statements in order.
No choices are made; there is no repetition.
Control structures provide alternatives to sequential program
execution and are used to alter the sequential flow of execution.
The two most common control structures are:
1) Selection
2) Repetition
Relational Operators
In a sequential program
The computer starts at the beginning and follows the statements in
order.
No choices are made; there is no repetition.
Control structures provide alternatives to sequential program
execution and are used to alter the sequential flow of execution.
The two most common control structures are:
1) Selection
2) Repetition
In selection, the program executes particular statements
depending on some condition(s).
In repetition, the program repeats particular statements a certain
number of times based on some condition(s)
Flow of Execution
Control structures
Consider the following statements:
1) if (score is greater than or equal to 90) grade is A
2) If (hours worked are less than or equal to 40)
wages = rate * hours
otherwise
wages = rate * 40 + 1.5 * rate * (hours – 40)
3) If (temperature is grater than 70 degree and it is not raining)
recommended activity is golfing
These are example of conditional statements
Some statements are executed only if certain conditions are met
A condition is met if it evaluates to true
Control structures
In C++, a condition is represented by a logical (Boolean)
expression.
An expression that has a value of either true or false is called a
logical (Boolean) expression.
True and false are logical (Boolean) values
Relational Operators in C++
Relational operators:
Allow comparisons
Require two operands (binary)
Expressions such as 4 < 6 and 'R' > 'T' are examples of logical
(Boolean) expressions.
Return 1 if expression is true, 0 otherwise
Comparing values of different data types may produce
unpredictable results
For example, 8 < '5' should not be done
Any nonzero value is treated as true
Relational Operators in C++
Relational Operators and Simple Data Types
Expression Meaning Value
8 < 15 8 is less than 15 true
6 != 6 6 is not equal to 6 false
2.5 > 5.8 2.5 is greater than 5.8 false
5.9 <= 7.5 5.9 is less than or equal to 7.5 true
Comparing characters
Relational Operators and the string Type
The relational operators can be applied to variables of type string.
Variables of type string are compared character by character,
starting with the first character and using the ASCII collating
sequence.
The character-by-character comparison continues until either
A mismatch is found or
The last characters have been compared and are equal.
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
Evaluating logical expressions with string variables
Evaluating logical expressions with string variables
Logical (Boolean) Operators and Logical
Expressions
Logical (Boolean) operators enable you to combine logical
expressions
In C++, there are three logical (Boolean) operators:
Logical (Boolean) Operators in C++
Logical (Boolean) Operators and Logical
Expressions
Logical operators take only logical values as operands and yield
only logical values as results.
The operator ! is unary, so it has only one operand.
The operators && and || are binary operators.
When you use the ! operator, !true is false and !false is true.
Putting ! in front of a logical expression reverses the value of that
logical expression
The ! (Not) Operator
Logical (Boolean) Operators and Logical
Expressions
Expression Value Explanation
!('A' > 'B') true Because 'A' > 'B' is false, !('A' > 'B')is true.
!(6 <= 7) false Because 6 <= 7 is true, !(6 <= 7) is false.
The && (And) Operator
The || (Or) Operator
Order of Precedence
Complex logical expressions can be difficult to evaluate.
Consider the following logical expression:
11 > 5 || 6 < 15 && 7 >= 8
This logical expression yields different results, depending on
whether || or && is evaluated first.
If || is evaluated first, the expression evaluates to false.
If && is evaluated first, the expression evaluates to true.
An expression might contain arithmetic, relational, and logical
operators, as in the expression:
5 + 3 <= 9 && 2 > 3
Precedence of Operators
Example 1
bool found = true;
bool flag = false;
int num = 1;
double x = 5.2;
double y = 3.4;
int a = 5, b = 8;
int n = 20;
char ch = 'B';
Expression Value
!found false
x > 4.0 true
!num false
!found && (x >= 0) false
!(found && (x >= 0)) false
x + y <= 20.5 true
(n >= 0) && (n <= 100) true
('A' <= ch && ch <= 'Z') true
(a + 2 <= b) && !flag true
Example 2
//Chapter 4: Logical operators
#include <iostream>
using namespace std;
int main()
{
bool found = true;
bool flag = false;
int num = 1;
double x = 5.2;
double y = 3.4;
int a = 5, b = 8;
int n = 20;
char ch = 'B';
cout<<"Line 1: !found evaluates to "
<<!found<<endl; //Line 1
cout<<"Line 2: x > 4.0 evaluates to "
<<(x > 4.0)<<endl; //Line 2
cout<<"Line 3: !num evaluates to "
<<!num<<endl; //Line 3
cout<<"Line 4: !found && (x >= 0) evaluates to "
<<(!found && (x >= 0))<<endl; //Line 4
cout<<"Line 5: !(found && (x >= 0)) evaluates to "
<<(!(found && (x >= 0)))<<endl; //Line 5
cout<<"Line 6: x + y <= 20.5 evaluates to "
<<(x + y <= 20.5)<<endl; //Line 6
cout<<"Line 7: (n >= 0) && (n <= 100) evaluates to "
<<((n >= 0) && (n <= 100))<<endl; //Line 7
cout<<"Line 8: ('A' <= ch && ch <= 'Z') evaluates to "
<<('A' <= ch && ch <= 'Z')<<endl; //Line 8
cout<<"Line 9: (a + 2 <= b) && !flag evaluates to "
<<((a + 2 <= b) && !flag)<<endl; //Line 9
return 0;
}
Output:
Line 1: !found evaluates to 0
Line 2: x > 4.0 evaluates to 1
Line 3: !num evaluates to 0
Line 4: !found && (x >= 0) evaluates to 0
Line 5: !(found && (x >= 0)) evaluates to 0
Line 6: x + y <= 20.5 evaluates to 1
Line 7: (n >= 0) && (n <= 100) evaluates to 1
Line 8: ('A' <= ch && ch <= 'Z') evaluates to 1
Line 9: (a + 2 <= b) && !flag evaluates to 1
Logical Expressions
You can insert parentheses into an expression to clarify its
meaning.
The expression
11 > 5 || 6 < 15 && 7 >= 8
is equivalent to
11 > 5 || (6 < 15 && 7 >= 8)
This logical expression evaluates to 1 (true).
Example
Evaluate the following expression:
(17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) && !(3 + 3 == 6)
= (17 < 4*3+5) || (8*2 == 4*4) && !(3+3 == 6)
= (17 < 12+5) || (16 == 16) && !(6 == 6)
= (17 < 17) || true && !(true)
= false || true && false
= false || false
= false
int Data Type and Logical (Boolean) Expressions
Earlier versions of C++ did not provide built-in data types that had
logical (or Boolean) values true and false.
Because logical expressions evaluate to either 1 or 0
the value of a logical expression was stored in a variable of the
data type int.
Therefore, you can use the int data type to manipulate logical
(Boolean) expressions
int Data Type and Logical (Boolean) Expressions
Remember that non-zero values are treated as true. Now,
consider the declarations:
int legalAge;
int age;
and the assignment statement:
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.
bool Data Type and Logical (Boolean) Expressions
Recent versions of C++ contains a built in data type, bool.
The data type bool, that has logical (Boolean) values true and
false.
In C++, bool, true, and false are reserved words.
The identifier true has the value 1 and the identifier false has the
value 0. Consider the declaration
bool legalAge;
The statement
legalAge = true;
Sets the value of the variable legalAge to true and the statement
legalAge = (age >= 21);
Assigns the value true to legalAge if the value of age is >= 21
bool Data Type and Logical (Boolean) Expressions
This statement assigns the value false to legalAge if the value of
age is less than 21.
For example, if the value of age is 25, the value assigned to legalAge
is true - that is, 1.
Similarly, if the value of age is 16, the value assigned to legalAge is
false - that is, 0.
You can use either an int variable or a bool variable to store the
value of a logical expression.
In this course use bool variables to store the values of logical
expressions
Selection: if and if...else
In C++, there are two selections, or branch control structures:
if statements and
the switch structure.
First we discusses how if and if...else statements can be used to
create one-way selection, two-way selection, and multiple
selections
One-Way Selection
In The syntax of one-way selection is:
if(expression)
statement
If the value of the expression is true, statement is executed;
If the value is false, statement is not executed and the computer
goes on to the next statement in the program.
The expression in the if statement is sometimes called a
decision-maker because it decides whether to execute the
statement or not.
The expression is usually a logical expression.
The statement following the expression is sometimes called
the action statement.
One-Way Selection
In The syntax of one-way selection is:
if(expression)
statement
If the value of the expression is true, statement is executed;
If the value is false, statement is not executed and the computer
goes on to the next statement in the program.
The expression in the if statement is sometimes called a
decision-maker because it decides whether to execute the
statement or not.
The expression is usually a logical expression.
statement is any C++ statement.
In C++, if is a reserved word.
One-Way Selection
One-Way Selection
In The syntax of one-way selection is:
if(expression)
statement
If the value of the expression is true, statement is executed;
If the value is false, statement is not executed and the computer
goes on to the next statement in the program.
The expression in the if statement is sometimes called a
decision-maker because it decides whether to execute the
statement or not.
The expression is usually a logical expression.
statement is any C++ statement.
In C++, if is a reserved word.
Example
if(score >= 60)
grade = 'P';
In this code,
If the expression (score >= 60) evaluates to true, the assignment
statement, grade = 'P';, executes.
If the expression evaluates to false, the statements (if any)
following the if structure execute.
For example, if the value of score is 65, the value assigned to the
variable grade is 'P'.
Example: The following C++ program finds the absolute
value of an integer:
#include <iostream>
using namespace std;
int main ()
{
int number;
cout<<"Please enter an integer--> "; //Line 1
cin>>number; //Line 2
if(number < 0) //Line 3
number = -number; //Line 4
cout<<endl<<"The absolute value is "
<<number<<endl; //Line 5
return 0;
}
Sample Run: The user input is red.
Please enter an integer --> -6734
The absolute value is 6734
One-Way Selection
Consider the following statement:
if score >= 90 //syntax error
grade = 'A';
This statement illustrates an incorrect version of an if statement.
The parentheses around the logical expression are missing, which
is a syntax error
To put a semicolon after the parentheses following the expression
(that is, before the statement) in an if statement in a one-way
selection is a semantic error.
The if statement, in such a case will operate on the empty
statement represented by the semi-colon.
One-Way Selection
Consider the following C++ statements:
if (score >= 60); //Line 1
grade = 'P'; //Line 2
Because there is a semicolon at the end of the expression (see
Line 1), the if statement in Line 1 terminates.
The action of this if statement is null, and the statement in Line 2
is not part of the if statement in Line 1.
Hence, the statement in Line 2 executes regardless of how the if
statement evaluates.
Two-way Selection
Two-way selection takes the form:
if(expression)
statement1
else
statement2
In a two-way selection if the value of the expression is true,
statement1 is executed.
If the value of the expression is false, statement2 is executed.
statement1 and statement2 are any C++ statements
In C++, else is a reserved word.
Two-way Selection
Two-way selection takes the form:
if(expression)
statement1
else
statement2
In a two-way selection if the value of the expression is true,
statement1 is executed.
If the value of the expression is false, statement2 is executed.
statement1 and statement2 are any C++ statements
In C++, else is a reserved word.
Two-way Selection
Two-way Selection
if(hours > 40.0) //Line 1
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0); //Line 2
else //Line 3
wages = hours * rate; //Line 4
If the value of the variable hours is greater than 40.0, then the wages
include overtime payment.
Suppose that hours is 50. The expression in the if statement at Line 1
evaluates to true, so the statement at Line 2 executes.
If hours is 30, or any number less than or equal to 40, the expression
in the if statement at Line 1 evaluates to false. The program skips the
statement at Line 2 and executes the statement at Line 4.
Two-way Selection
In a two-way selection statement, putting a semicolon after
the expression and before statement1 creates a syntax error.
If the if statement ends with a semicolon, statement1 is no longer
part of the if statement, and the else part of the if. . .else
statement stands all by itself.
There is no standalone else statement in C++. That is, it cannot be
separated from the if statement. The following statements show an
example of a syntax error.
if(hours > 40.0); //Line 1
wages = 40.0 * rate +
1.5 * rate* (hours - 40.0); //Line 2
else //Line 3
wages = hours * rate; //Line 4
Two-way Selection
Because a semicolon follows the closing parenthesis of the if
statement (Line 1), the else statement stands alone.
The semicolon at the end of if statement (see Line 1) ends the if
statement, so the statement at Line 2 separates the else clause
from the if statement. That is, else is all by itself.
Since there is no else statement in C++, this code generates a
syntax error.
Example
//Program: Weekly wages
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double wages, rate, hours;
cout<<fixed<<setprecision(2); //Line 1
cout<<"Line 2: Enter working hours and rate: ";
//Line 2
cin>>hours>>rate; //Line 3
if(hours > 40.0) //Line 4
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0); //Line 5
else //Line 6
wages = hours * rate; //Line 7
cout<<endl; //Line 8
cout<<"Line 9: The wages are $"<< wages<<endl;
//Line 9
return 0;
}
Sample Run: The user input is in red.
Line 2: Enter working hours and rate: 56.45 12.50
Line 9: The wages are $808.44
Example
if(score >= 90)
grade = 'A';
cout<<"The grade is "<<grade<<endl;
These statements contain a semantic error.
The if statement acts on only one statement, which is grade = 'A';.
The cout statement executes regardless of whether
(score >= 90) is true or false.
Example
if(score >= 60)
cout<<"Passing"<<endl;
cout<<"Failing"<<endl;
If the expression (score >= 60) evaluates to false, the output is
Failing.
For example, if the value of score is 50, these statements will
output the following line:
Failing
If the expression score >= 60 evaluates to true, the program will
write both statements, giving a very unsatisfactory result.
Example
If the value of score is 70, these statements will output the
following lines:
Passing
Failing
The correct code to print Passing or Failing, depending on the
value of score, is
if(score >= 60)
cout<<"Passing"<<endl;
else
cout<<"Failing"<<endl;
Compound (Block of) Statement
C++ provides a structure called a compound statement or a
block of statements. A compound statement takes the following
form:
{
statement 1;
statement 2;
.
.
.
statement n;
}
A compound statement consists of a sequence of statements
enclosed in curly braces, {and }.
Compound (Block of) Statement
A compound statement is considered a single statement.
In an if or if . . .else structure, a compound statement functions as
if it was a single statement
Thus, instead of a simple two-way selection as represented by
if(age > 18)
cout<<"Eligible to vote."<<endl;
else
cout<<"Not eligible to vote."<<endl;
Compound (Block of) Statement
We may substitute the compound 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;
}
Compound (Block of) Statement
We may substitute the compound 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;
}
Multiple Selections: Nested if
There is a way of considering multiple selections using if...else, if
we permit the action statement itself to be an if... statement.
When one control statement is within another, it is said to be
nested.
Consider the following statement. (Assume that all variables are
properly declared.)
Syntax
if (testCondition1)
{
// statements to be executed if testCondition11 is true
}
else if(testCondition2)
{
// statements to be executed if testCondition1 is false and testCondition2 is true
}
else if (testCondition3)
{
// statements to be executed if testCondition1 and testCondition2 is false and
testCondition3 is true
}
.
.
else
{
// statements to be executed if all test conditions are false
}
Example
Assume that all variables are properly declared, and consider the
following statements:
if(score >= 90)
cout<<"The grade is A"<<endl;
else if(score >= 80)
cout<<"The grade is B"<<endl;
else if(score >= 70)
cout<<"The grade is C"<<endl;
else if(score >= 60)
cout<<"The grade is D"<<endl;
else
cout<<"The grade is F"<<endl;
More example
if(month == 1) //Line 1
cout<<"January"<<endl; //Line 2
else if(month == 2) //Line 3
cout<<"February"<<endl; //Line 4
else if(month == 3) //Line 5
cout<<"March"<<endl; //Line 6
else if(month == 4) //Line 7
cout<<"April"<<endl; //Line 8
else if(month == 5) //Line 9
cout<<"May"<<endl; //Line 10
else if(month == 6) //Line 11
cout<<"June"<<endl; //Line 12
switch Structures
The general form (syntax) of a switch statement is:
switch(expression)
{
case value1: statements1;
break;
case value2: statements2;
break;
.
.
.
case valuen: statementsn;
break;
default: statements;
}
switch Structures
The break statement has a special meaning and may or may not
appear after each statement.
In C++, switch, case, break, and default are reserved words.
In a switch structure, first the expression is evaluated.
The value of the expression is then used to perform the
corresponding action.
Although it need not be, the expression is usually an identifier.
The value of the expression can be only integral.
The expression is sometimes called the selector.
Its value determines which case is selected for execution.
switch Structures
A particular case value should appear only once.
One or more statements may follow a case label, so you do not
need to use braces to turn multiple statements into a single
compound statement.
The break statement may or may not appear after each statement
switch Structures
The switch statement executes according to the following rules:
1) When the value of the expression is matched against a
case value (also called a label), the statements execute until
either a break statement is found or the end of the switch
structure is reached
2) If the value of the expression does not match any of the case
values, the statements following the default label execute. If
the switch structure has no default label, and if the value of the
expression does not match any of the case values, the entire
switch statement is skipped.
3) A break statement causes an immediate exit from the switch
structure.
Example 1:
switch(grade)
{
case 'A': cout<<"The grade is A.";
break;
case 'B': cout<<"The grade is B.";
break;
case 'C': cout<<"The grade is C.";
break;
case 'D': cout<<"The grade is D.";
break;
case 'F': cout<<"The grade is F.";
break;
default: cout<<"The grade is invalid.";
}
Where, grade is a variable of the type char. If the value of grade is,
say 'A', the output is The grade is A.
Example 2
//Program: Effect of break statements in a switch structure
#include <iostream>
using namespace std;
int main ()
{
int a;
cout<<"Enter an integer between 0 and 10: "; //Line 1
cin>>a; //Line 2
cout<<"\nThe number you entered is "<<a<<endl; //Line 3
switch(a) //Line 4
{
case 0: //Line 5
case 1: cout<<"Hello "; //Line 6
case 2: cout<<"there. "; //Line 7
case 3: cout<<"I am "; //Line 8
case 4: cout<<"Mickey."<<endl; //Line 9
break; //Line 10
case 5: cout<<"How "; //Line 11
case 6: //Line 12
case 7: //Line 13
case 8: cout<<"are you?"<<endl; //Line 14
break; //Line 15
case 9: break; //Line 16
case 10: cout<<"Have a nice day."<<endl; //Line 17
break; //Line 18
default: cout<<"Sorry number is out of "
<<"range."<<endl; //Line 19
}
cout<<"Out of switch structure."<<endl; //Line 20
return 0;
}
Sample Run: In these sample runs, the user input
is in red.
Sample Run 1:
Enter an integer between 0 and 10: 0
The number you entered is 0
Hello there. I am Mickey.
Out of switch structure.
Sample Run 2:
Enter an integer between 0 and 10: 1
The number you entered is 1
Hello there. I am Mickey.
Out of switch structure.
Sample Run 3:
Enter an integer between 0 and 10: 3
The number you entered is 3
I am Mickey.
Out of switch structure.
Sample Run 4:
Enter an integer between 0 and 10: 4
The number you entered is 4
Mickey.
Out of switch structure.
Sample Run 5:
Enter an integer between 0 and 10: 5
The number you entered is 5
How are you?
Out of switch structure.
Sample Run 6:
Enter an integer between 0 and 10: 7
The number you entered is 7
are you?
Out of switch structure.
Sample Run 9:
Enter an integer between 0 and 10: 11
The number you entered is 11
Sorry number is out of range.
Out of switch structure.
Sample Run 5:
Enter an integer between 0 and 10: 5
The number you entered is 5
How are you?
Out of switch structure.
Sample Run 6:
Enter an integer between 0 and 10: 7
The number you entered is 7
are you?
Out of switch structure.
Example 3:
Assume that score is an int variable with values between 0 and 100
switch(score / 10)
{
case 0: case 1: case 2:
case 3: case 4: case 5: grade = 'F';
break;
case 6: grade = 'D';
break;
case 7: grade = 'C';
break;
case 8: grade = 'B';
break;
case 9: case 10: grade = 'A';
break;
default: cout<<" Invalid test score."<<endl;
}
Example 4:
In the following C++ code, the switch expression evaluates to a logical
value.
switch(age >= 18)
{
case 1: cout<<"Old enough to be drafted."<<endl;
cout<<"Old enough to vote."<<endl;
break;
case 0: cout<<"Not old enough to be drafted."<<endl;
cout<<"Not old enough to vote."<<endl;
}
Example 5:
The following switch statement is equivalent to the previous switch
statement.
switch(age >= 18)
{
case true: cout<<"Old enough to be drafted."<<endl;
cout<<"Old enough to vote."<<endl;
break;
case false: cout<<"Not old enough to be drafted.”
<<endl;
cout<<"Not old enough to vote."<<endl;
}
End of Lecture