Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 65

CHAPTER 4

SELECTION STRUCTURE

Contents
Introduction
Selection criteria with Boolean
expression
The if statement
The if..else statement
The if..else if statement
Nested if statement
The switch statement



CSC425 - SEPTEMBER 2013
Introduction
A computer can proceed:
In sequence
Selectively (branch) - making a choice
Repetitively (iteratively) - looping
Some statements are executed only if
certain conditions are met
A condition is represented by a logical
(Boolean) expression that can be true or
false
A condition is met if it evaluates to true

CSC425 - SEPTEMBER 2013
Introduction
Flow of Control: the order in which a
programs statements are executed
Normal flow is sequential
Selection and Repetition Statements allow
programmer to alter normal flow
Selection: selects a particular statement to
be executed next
Selection is from a well-defined set
Repetition: allows a set of statements to be
repeated
CSC425 - SEPTEMBER 2013
Introduction

CSC425 - SEPTEMBER 2013
Introduction
CSC425 - SEPTEMBER 2013
Selection
Selection criteria with Boolean expression
Boolean expression is a sequence of
operands and operators that combine to
produce one of the Boolean values, true or
false.
2 types of Boolean expression :
- simple Boolean expression
- compound Boolean expression

CSC425 - SEPTEMBER 2013
Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Simple Boolean expression :
is of the form

expression1 relational-operator expression2

Relational operators:
Allow comparisons
Require two operands
Return 1 if expression is true, 0 otherwise

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
All computers are able to compare numbers
Can be used to create an intelligence-like facility
Relational Expressions: expressions used to
compare operands
Format: a relational operator connecting two
variable and/or constant operands
Examples of valid relational expressions:

Age > 40 length <= 50 flag == done

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Relational operators can be any of the following operators :
Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Relational Expressions (conditions):
Are evaluated to yield a numerical result
Condition that is true evaluates to 1
Condition that is false evaluates to 0
Example:
The relationship 2.0 > 3.3 is always false,
therefore the expression has a value of 0


Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Comparing string Types :
Relational operators can be applied to strings
Strings are compared character by character,
starting with the first character
Suppose we have the following declarations:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";


Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Compound Boolean expression :
is formed by combining simple Boolean expressions with the
following logical operator :



Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
More complex conditions can be created using
logical operations AND, OR, and NOT
Represented by the symbols: &&, ||, !
AND Operator, &&:
Used with 2 simple expressions
Example: (age > 40) && (term < 10)
Compound condition is true (has value of 1)
only if age > 40 and term < 10

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
OR Operator, ||:
Used with 2 simple expressions
Example: (age > 40) || (term <
10)
Compound condition is true if age > 40 or
if term < 10 or if both conditions are true
NOT Operator, !:
Changes an expression to its opposite state
If expressionA is true, then
!expressionA is false

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
For example, the expression such as
5 <= x <= 10

can be written as the following
compound Boolean expression:
(5 <= x) && ( x <= 10)


Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013
Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013

Selection criteria with Boolean expression
CSC425 - SEPTEMBER 2013

One way selection:
The if statement
The purpose of the if-else statement is to
choose between different actions that must
be taken based on the certain condition.

It is used to implement such a decision
structure in its simplest form, which is
choosing between two alternatives.
CSC425 - SEPTEMBER 2013
The if statement
CSC425 - SEPTEMBER 2013
if (expression) {


Statement;


}
The if statement
Used in a one-way selection
The syntax :
if (condition)
statement;
statement is executed if the value of the
condition is true
statement is bypassed if the value of the
condition is false; program goes to the
next statement

CSC425 - SEPTEMBER 2013
The if statement (Program 1: Find absolute
value)
#include <iostream>
using namespace std;
int main( )
{
int number, temp;
cout << "Please enter an integer:";
cin >> number;
temp = number;

if (number <0)
number= -number;
cout << "The absolute value of " << temp << " is"<<
number <<endl;
system("PAUSE");
return 0;}
CSC425 - SEPTEMBER 2013
Only be executed if number < 0 is equal
to true
The if statement
The condition used in an if statement can be
any valid C++ expression. But the most
commonly used expressions are called
relational expressions. A simple relational
expression consists of a relational operator that
compares two operands:

CSC425 - SEPTEMBER 2013
If ( Volts < =35.2)

Volts and 35.2 ---> operand
< = ---- >relational operator

The if statement
Used in a selection execution. Syntax:
If (condition)
statement
The statement following if (expression) is
executed only if the expression is true
Example
if (hours > 40.0)
{
overtime = hours 40.0;
overtime_pay = 1.5 * overtime * rate;
}
cout << " Overtime pay is " << overtime_pay;

CSC425 - SEPTEMBER 2013
The if statement (Program 2 : Mileage)
CSC425 - SEPTEMBER 2013
The constant value for mileage limit is 3000.0. This
program will retrieve input about car id and
mileage from user. If mileage greater than
mileage limit, then the program will output as
Car id is over the limit
The if statement (Program 2 : Mileage)
CSC425 - SEPTEMBER 2013
#include <iostream>
using namespace std;
int main( )
{
const double mileage_limit = 3000.0;
int car_id;
double mileage;

cout << " Please type in car number and mileage: ";
cin >> car_id >> mileage;

if (mileage > mileage_limit )
cout << "Car" << car_id << "is over the limit." << endl;
cout << "End of program output.";
system ("PAUSE");
return 0;
}
The if statement (Program 2 : Mileage)
Run twice with different input data
Result 1:





Result 2:
CSC425 - SEPTEMBER 2013
Please type in car number and mileage:
256 3562.8
Car 256 is over the limit.
End of program output.

Please type in car number and mileage:
23 2562.8
End of program output.

Two way selection:
The if..else statement
Two-way selection takes the form:
if (expression)
statement1;
else
statement2;
If expression is true, statement1 is executed
otherwise statement2 is executed
statement1 and statement2 are any C++
statements
else is a reserved word
CSC425 - SEPTEMBER 2013
The if..else statement
Selects a sequence of one or more instructions
based on the results of a comparison
General form:
if (expression) <- no semicolon
here
statement1;
else <- no semicolon here
statement2;

If the value of expression is true, statement1 is
executed
If the value is false, statement2 is executed
CSC425 - SEPTEMBER 2013
Two way selection:
The if..else statement
CSC425 - SEPTEMBER 2013
if (expression) {

statement1;

}
else {

statement2;

}
The if..else statement
if final_score >= 60

status = pass
else

status = fail
CSC425 - SEPTEMBER 2013
if.else statement (Program 3:
Mileage)
CSC425 - SEPTEMBER 2013
The constant value for mileage limit is 3000.0.
This program will retrieve input about car id and
mileage from user. If mileage greater than
mileage limit, then the program will give the
output Car id is over the limit else the
program will give the output Car id is NOT
over the limit.
The if else statement (Program 3 : Mileage)
CSC425 - SEPTEMBER 2013
#include <iostream>
using namespace std;
int main( )
{
const double mileage_limit = 3000.0;
int car_id;
double mileage;
cout << " Please type in car number and mileage: ";
cin >> car_id >> mileage;

if (mileage > mileage_limit )
cout << "Car" << car_id << "is over the limit." << endl;
else
cout << "Car" << car_id << "is NOT over the limit." <<
endl;
cout << "End of program output.";
system ("PAUSE");
return 0;
}
The if else statement (Program 3 : Mileage)
Run twice with different input data
Result 1:





Result 2:
CSC425 - SEPTEMBER 2013
Please type in car number and mileage:
256 3562.8
Car 256 is over the limit.
End of program output.

Please type in car number and mileage:
23 2562.8
Car 256 is NOT over the limit.
End of program output.

The if..else statement (Program 4 : Taxes)
CSC425 - SEPTEMBER 2013
This program wants to calculate the amount of
taxes. It will requires the user to key in their
taxable income. If the taxable is less than and
equal 20000.0, the taxes = 0.02 * taxable. Else,
the taxes = 0.025*(taxable-20000.0)+400.0
This program will give the output of taxes in two
decimal places.
The if..else statement (Program 4 : Taxes)
CSC425 - SEPTEMBER 2013
#include <iostream>
#include <iomanip>
using namespace std;
int main( )
{
float taxable,taxes;
cout << "Please type in the taxable income:";
cin >> taxable;
if (taxable <= 20000.0)
taxes = 0.02 * taxable;
else
taxes = 0.025*(taxable-20000.0)+400.0;
cout << fixed<<showpoint<< setprecision(2)<< "Taxes
are $ " <<taxes<<endl;
system ("PAUSE");
return 0;}
The if..else statement (Program 5)
#include <iostream>
int main(){
int x;
cout << Please enter a number : << endl;
cin >> x;

if( x < 10)
cout << ******* << endl;
else
cout << ##### << endl;

return 0;
}
CSC425 - SEPTEMBER 2013
The if..else statement (Program 6)
Produce one program that will output:

number entered is odd or
number entered is even

Base on the input number from user.

Example output:

Please enter a number: 19
The number you have entered is odd
CSC425 - SEPTEMBER 2013
The if..else statement (Compound
statement)
Compound statement (block of statements):
{
statement1;
statement2;
.
.
.
statementn;
}

CSC425 - SEPTEMBER 2013
The if..else statement (Compound statement)
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;
}

CSC425 - SEPTEMBER 2013
The if..else if.. statement
CSC425 - SEPTEMBER 2013
if (condition1)
statement1;
else if(condition2)
statement2;
else if (condition3)
statement3;
else if (condition_n)
statement_n;
else
statement_e;
If more than 2 conditions, used if else if as in the general form below:
The if else if.statement (Program 7
Score)

pair
pair
pair
pair
CSC425 - SEPTEMBER 2013
The if else if statement (Program 8: Letter_input)
CSC425 - SEPTEMBER 2013
The program displays an items specification
status corresponding to a letter input. The
following letter codes are used :
Specification Status Input Code
Space Exploration S/s
Military Grade M/m
Commercial Grade C/c
Toy Grade T/t
CSC425 - SEPTEMBER 2013
#include <iostream>
using namespace std;
int main() {
char code;
cout << Enter a specification code:;
cin >> code;
if(code ==S || s)
cout << \n The item is space exploration grade;
else if (code ==
else if(code ==M || m)
cout << \n The item is military grade;
else if(code ==C || c)
cout << \n The item is commercial grade;
else if(code ==T || t)
cout << \n The item is toy grade;
else
cout << \n An invalid code was entered << endl;
system (PAUSE);
return 0;



Nested if statement
One or more if statement can be included
within either part of an if statement.
Inclusion of one or more if statement within
an existing if statement called a nested if
statement
CSC425 - SEPTEMBER 2013
Nested if statement (Program 9)

#include <iostream>
int main(){
int x, y;

cout << Please enter two number : << endl;
cin >> x >> y;

if( x < 10)
if( y > 10)
cout << ******* << endl;
else
cout << ##### << endl;
cout << $$$$$ << endl;
return 0;
}
CSC425 - SEPTEMBER 2013
Nested if statement (Program 10-
GPA)
CSC425 - SEPTEMBER 2013
If GPA is greater and equal 2, you have to check,
if GPA is less than 3.9, the output is Happy
Graduation. If GPA is greater and equal 3.9, the
out is Deans Honor List. If GPA less than 2.0, the
output is Current GPS is below graduation
requirement, See your academic advisor.
Nested if statement (Program 10 : GPA)
CSC425 - SEPTEMBER 2013
Nested if statement (Program 11 :
Aircraft)
Consider the following case :

Nations Air force has asked you to write a program to
label supersonic aircraft as military or civilian. Your program is
to be given the planes observed speed in km/h and its estimated
length in meters. For planes traveling in excess of 1100km/h,
you will label those longer than 52 meters civilian and shorter
aircraft as military. For planes traveling at slower speeds, you
will issue an aircraft type unknown message.

CSC425 - SEPTEMBER 2013
Nested if statement (Program 11 : Aircraft)
CSC425 - SEPTEMBER 2013
Switch Case
CSC425 - SEPTEMBER 2013
The switch statement provides an alternative to the if-
else chain for cases that compare the value of an
integer expression to a specific value. General form
of switch statement :
switch (expression){
case value1 :
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
default:
statement_n;
}
Switch Case (Program 12 : Arithmetic
operation)
CSC425 - SEPTEMBER 2013
Program to select the arithmetic operations
(addition, multiplication) to be performed on two
numbers depending on the value of the variable
op_select.
Switch Case (Program 12 : Arithmetic
Operation)
CSC425 - SEPTEMBER 2013
#include <iostream>
using namespace std;
int main () {
int op_select;
double fnum,snum,sum,prod,quot;
cout << please type in two numbers: ;
cin >> fnum >> snum;
cout << enter a select code:
cout << /n 1 for addition;
cout << /n 2 for multiplication;
cout << /n enter selection;
cin >> op_select;
CSC425 - SEPTEMBER 2013
switch (op_select){
case 1:
sum = fnum + snum;
cout << the sum is << sum << endl;
break;
case 2:
sum = fnum*snum;
cout << the product is << sum << endl;
break;
default:
cout << invalid selection. << endl;
}
system(pause);
return 0;
Switch Case (Program 12 : Cont)
CSC425 - SEPTEMBER 2013
Q&A
Exercise
1) Suppose the input is 5. What is the value of alpha
after the following code executes?
switch(alpha)
{
case 1: alpha = alpha + 2;
case 4: alpha++;
break;
case 5: alpha = 2 * alpha;
case 6: alpha = alpha + 5;
break;
default: alpha- -;
}

CSC425 - SEPTEMBER 2013
Exercise
2) Write a program that reads the users age and then
print You are a child if the age is below 18, you
are an adult for age 18 to 65, you are senior
citizen if age is 65 and above.


3) Write a program that simulates a simple calculator.
It reads two integer and a character. If character is
+ ,the sum is printed; if it is -,the differences is
printed; if it is *, the product is printed; if it is /,the
quotient is printed; and if it is %, the remainder is
printed. Use switch statement.
CSC425 - SEPTEMBER 2013
4) A mail order house sells five different products
whose retail prices for product 1 is RM2.98,
product 2 is RM4.50, product 3 is RM9.98,
product 4 is RM4.49, product 5 is RM 6.87.

Write a program that reads a series of pairs of
number as follows:
a) product number
b) quantity sold for one day.

Use switch statement to help determine the
retail price (total sold price for each product)


CSC425 - SEPTEMBER 2013

You might also like