0% found this document useful (0 votes)
2 views

C-- 03 Edu

The document provides an overview of selection statements in C++, focusing on relational operators, the if statement, if/else structures, and the switch statement. It explains how to use these constructs to control the flow of a program based on conditions, including examples and best practices for formatting. Additionally, it covers logical operators, conditional expressions, and the requirements for using switch statements.

Uploaded by

bd103247
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C-- 03 Edu

The document provides an overview of selection statements in C++, focusing on relational operators, the if statement, if/else structures, and the switch statement. It explains how to use these constructs to control the flow of a program based on conditions, including examples and best practices for formatting. Additionally, it covers logical operators, conditional expressions, and the requirements for using switch statements.

Uploaded by

bd103247
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 24

C++ Programming

3. Selection

Prof. Moheb Ramzy Girgis


Department of Computer Science
Faculty of Science
Minia University
Relational Operators
 Used to compare numeric values to determine
relative order
 Operators:
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=
Equal to ==
Not equal to !=

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 2
Relational Expressions
 Relational expressions are Boolean (i.e., evaluate
to true or false)
 Examples:
12 > 5 is true
7 <= 5 is false
if x is 10, then
x == 10 is true
x <= 8 is false
x != 8 is true
x == 8 is false

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 3
The if Statement
 Supports the use of a decision structure
 Allows statements to be conditionally executed or skipped
over
 Models the way we mentally evaluate situations
“If it is cold outside,
wear a coat and wear a hat.”
 Format of the if Statement No ; goes here
if (condition)
{
statement1;
statement2; ; goes here

statementn;
}
 The block inside the braces is called the body of the if
statement. If there is only 1 statement in the body, the { }
may be omitted C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 4
How the if Statement Works
 If (condition) is true, then
the statement(s) in the
body are executed. condition
 If (condition) is false,
then the statement(s) are
true false
skipped.
1 or more
statements
if Statement
Flow Chart

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 5
if Statements Example
if (score >= 60)
cout << "You passed." << endl;
if (score >= 90)
{
grade = 'A';
cout << "Wonderful job!" << endl;
}
 if Statement Notes
 if is a keyword. It must be lowercase

 Condition must be in ( )

 Do not place ; after (condition)

 Don't forget the { } around a multi-statement body

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 6
if Statement Style
Recommendations
 Place each statement; on a separate line after

(condition)
 Indent each statement in the body
 When using { and } around the body, put { and } on lines
by themselves

What is true and false?


 An expression whose value is 0 is considered false.
 An expression whose value is non-zero is considered
true.
 An expression need not be a comparison – it can be a
single variable or a mathematical expression.

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 7
The if/else Statement
 Allows a choice between statements depending on
whether (condition) is true or false
 Format:
if (condition)
{
statement set 1;
} true condition false
else
{
statement set 2;
} statement statement
set 1 set 2
if/else Flow
Chart

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 8
How the if/else Works
 If (condition) is true, statement set 1 is executed
and statement set 2 is skipped.
 If (condition) is false, statement set 1 is skipped
and statement set 2 is executed.
 Examples:  Pass/Fail
if (score >= 60)
 Maximum of two cout << “Pass";
numbers: else
if (a > b) cout << “Fail";
max = a;  Interest/No interest
else if (balance > 100)
max = b; {
cout << “maximum is “ Interest = balance * intRate;
<< max; cout << interest;
}
else
cout << “No interest.\n";
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 9
The if/else if Statement
 The if / else if statement is a chain of if statements. They
perform their tests, one after the other, until one of them is
found to be true.
 We make certain mental decisions by using sets of
different but related rules.
 For example, we might decide the type of coat or jacket to
wear by consulting the following rules:
if it is very cold, wear a heavy coat,
else, if it is chilly, wear a light jacket,
else, if it is windy, wear a windbreaker,
else, if it is hot, wear no jacket.
 In C++, this can be accomplished through the if/else if
statement.
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 10
if/else if Format

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 11
The if/else if Statement
 An if condition in the if/else if structure is tested only when
all the if conditions before it are false.
 The statements following a particular else if are executed
when the condition associated with that else if is true and
all previous conditions are false.
 The if/else if structure stops doing comparisons as soon
as it finds a condition that is true.
 (Ex: The grades program)
 Note:
 If you have several conditions and every condition must be
tested, then use an independent if statement for each
condition.
(Ex: The maximum of three numbers program)
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 12
Using a Trailing else
 A final else that is placed at the end of an if/else if
statement is called a trailing else.
 A trailing else is used with if/else if statement when all
of the conditions are false.
 It provides a default statement Example
or action that is performed when if (age >= 21)
none of the conditions is true. cout << "Adult";
 It can be used to catch invalid else if (age >= 13)
values or handle other cout << "Teen";
exceptional situations. else if (age >= 2)
cout << "Child";
else
cout << "Baby";
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 13
Nested if Statements
 It is possible for one if statement or if/else statement to be
placed inside another one.
 This construct, called a nested if, allows you to test more
than one condition to determine which block of code should
be executed.  if (score < 100)
if (score < 100)
if (score > 90)
{
grade = 'A';
if (score > 90)
else ...
grade = 'A';
} goes with second if,
 Note: not first one
 An else matches the nearest previous if that does not

have an else, (see the example in the box)


 Proper indentation aids comprehension
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 14
Logical Operators
 In the previous slide you saw how a program tests two
conditions with two if statements.
 Now you will see how to use logical operators to combine
two or more relational expressions into one.
 Logical operators connect two or more relational
expressions into one or reverse the logic of an expression.
 Logical Operators:

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 15
Logical Operator Examples
int x = 12, y = 5, z = -4;
Value Logical Expression
true (x > y) && (y > z)
false (x > y) && (z > y)
false (x <= z) || (y == z)
true (x <= z) || (y != z)
false !(x >= z)

16
Logical Precedence
Highest !
&&
Lowest ||
Example:
(2 < 3) || (5 > 6) && (7 > 8)

is true because AND is evaluated before OR


 Precedence of all operators: arithmetic operators Highest
relational operators
logical operators Lowest
 Example:
8 < 2 + 7 || 5 == 6 is true

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 17
Checking Numeric Ranges with
Logical Operators
 Used to test if a value is within a range: 0 ≤ grade ≤ 100
if (grade >= 0 && grade <= 100)
cout << "Valid grade";
 Can also test if a value lies outside a range: 0 > grade > 100
if (grade < 0 || grade > 100)
cout << "Invalid grade";
 Cannot use mathematical notation
if (0 <= grade <= 100) //Doesn’t work!

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 18
The Conditional Operator
 It can be used to create short if/else statements
 Format: expr ? expr : expr;
 Example:
 This conditional
expression is
equivalent to this if
I else statement:

 An example of an assignment
statement that uses the value of a
conditional expression:
a = (x > 100) ? 0 : 1; Equivalent to
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 19
The switch Statement
 The switch statement is used to select among statements
from several alternatives.
 It may sometimes be used instead of if/else if
statements
 It tests the value of an integer expression and then uses that
value to determine which set of statements to branch to.
 The switch Statement Format:
switch (IntExpression)
{
case exp1: statement set 1;
break;
case exp2: statement set 2;
break;
...
case expn: statement set n;
break;
default: statement set n+1;
C++ Programming - Prof. Moheb Ramzy
} Girgis Dept. of Computer Science -
Faculty of Science Minia University 20
switch Statement
Requirements
1)IntExpression can be either of the following:
 A variable of any of the integer data types (including
char).
 An expression whose value is of any of the integer data

types.
2)exp1 through expn must be constant integer type
expressions and must be unique in the switch statement
3)default is optional but recommended. It is branched to if
none of the case expressions match the switch expression.
Thus, it functions like a trailing else in an ifI else if
statement.

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 21
How the switch Statement
Works
1) IntExpression is
evaluated
IntExpression Yes
2) The value of == exp1
statement set 1 break

intExpression is
compared against exp1
No

through expn. IntExpression Yes


statement set 2 break
3) If IntExpression == exp2

matches value expi, the No

program branches to the


statement(s) following
expi and continues to the Yes
end of the switch IntExpression
== expn
statement set n break

4) If no matching value is No
found, the program statement(s)-for-
branches to the statement default

after default
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 22
How the switch Statement Works
(Continued)
 Notice that each case ends with a break statement.

 The break statement causes the program to exit the switch


statement.
 The next statement executed after encountering a break
statement will be whatever statement follows the closing
brace that terminates the entire switch statement.
 A break statement is needed whenever you want to "break
out of" a switch statement.
 The default section (or the last case section if there is no
default ) does not need a break statement.

C++ Programming - Prof. Moheb Ramzy


Girgis Dept. of Computer Science -
Faculty of Science Minia University 23
switch Statement Example
char gender;
cout << "Enter a gender: ";
cin >> gender;
switch (gender)
{
case 'f': cout << "female";
break;
case 'm': cout << "male";
break;
default : cout << "invalid gender";
}
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 24

You might also like