You are on page 1of 72

1

CSC128: TOPIC 3
SELECTION CONTROL STRUCTURE
2

LEARNING
OUTCOMES
✓ To learn about control structures
✓ To examine relational and logical
operators
✓ To explore on how to form and evaluate
logical (Boolean) expressions
✓ To discover how to use the selection
control structures if, if...else in a program
3

INTRODUCTION
What does it mean
when a program is
executed
SEQUENTIALLY?
4
CONTROL STRUCTURES
Computer program can be executed:
i. In Sequence
ii. By Selection (Branch): Making a choice
iii. By Repetition (Iterative): Looping

statement1
expression
statement1

expression statement

statementN statement2 statement1

a. Sequence b. Selection c. Repetition


5
• Allows a computer program to
make decisions
• Able to control the flow of the
program based on the decision
made SELECTION
• Decision is made by evaluating
the conditions given, which can STRUCTURE
either be:
Boolean expression
expression

TRUE FALSE
•Condition is met •Condition is NOT met
•Represents 1 •Represents 0 statement2 statement1
6
RELATIONAL OPERATORS
• Are used to compare values between 2 operands (are the
numbers)
• The result of comparison will either be:
✓ True Relation Description Example
× False Operator
== Equal to x == y
!= Not equal to x != y
< Less than x<y
<= Less than or equal to x <= y
> Greater than x>y
>= Greater than or equal to x >= y
7
RELATIONAL OPERATORS
1 (7 == 5) // evaluates to false
2 (5 > 4) // evaluates to true
3 (3 != 2) // evaluates to true
4 (6 >= 6) // evaluates to true
5 (5 < 5) // evaluates to false
8
RELATIONAL OPERATORS
• Suppose that a=2, b=3 and c=6, then:
1 (a == 5)//evaluates to false, since a is not equal to 5
2 (a*b >= c)//evaluates to true, since (2*3 >= 6) is true
3 (b+4 > a*c)//evaluates to false, since(3+4>2*6)is false
4 ((b=2) == a)// evaluates to ? true

2 is assigned (=) to variable b [the current value in b is now 2], and


the comparison equal to (==) is evaluated.
Is b equal to a?
Thus, the condition is evaluated to TRUE.
9
MAR 2017 PRACTICE 1

Answer: C
10
PRACTICE 2
Evaluate these conditional statements:
1. Suppose that a = 4 and b = 10, then:
• a < b
• b == a
• a >= b
2. Suppose that a = 7 and b = 5, then:
• a != b
• a > b
• b <= 7
11

LOGICAL OPERATORS
• Are used when there are more than one relational
expression to evaluate at a time
• Allows you to combine the relational expressions
• The result of comparison will either be:
✓ True Operator
Logical Description Unary or
Binary
Rule Example

× False Operator
Unary Produce ! (a < b)
! NOT opposite
relation
Binary Both operand (a < b) && (a < c)
&& AND must be true
Binary At least ONE (a == b) || (a == c)
|| OR (1) operand
must be true
12

LOGICAL OPERATORS
! NOT
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true
!(6 <= 4) // evaluates to true because (6 <= 4) would be false
!true // evaluates to false
!false // evaluates to true

&& AND || OR
&& OPERATOR (and)
|| OPERATOR (or)
a b a && b a b a || b
true true true true true true
true false false true false true
false true false false true true
false false false
false false false
13
MAR 2014 EXAMPLE 1

Answer: C
14
EXERCISE 1
Evaluate these conditional statements:

NOT ! OR ||
i. !(4 > 8) i. (5 < 7) || (9 > 4)
ii. !(6 <= 7) ii. (5 > 8) || (6 < 2)

AND &&
i. (3 < 9) && (10 > 2)
ii. (3 > 6) && (4 < 6)
15

ORDER OF PRECEDENCE
• Determine the order of evaluation in an expression
OPERATORS PRECEDENCE
!, +, - (UNARY OPERATORS) FIRST
*, /, % SECOND
+, - THIRD
<, <=, >=, > FOURTH
==, != FIFTH
&& SIXTH
|| SEVENTH
= (ASSIGNMENT OPERATOR) LAST
16
PRACTICE 3
Evaluate these conditional statements:
Suppose that x = 3, y = 4 and z = 5, then:

1 (x > y) && (y < z)


2 (x == y) || (x == z)
3 ! (z < y)
17
APR 2009 EXAMPLE 2

CAUTION: = is NOT the same with ==


x = y; //read: value of y is assigned to x
if(x==y) //read: if value of x is equal to value of y

Answer: D
18
MAR 2015 EXERCISE 2
PART B – QUESTION 1 (c)

Answer:
i) 1
ii) 0
TYPES OF SELECTION CONTROL
19 STRUCTURE

One-Way Two-ways Multiple


Selection selection selection
20

TYPES OF
SELECTION ONE WAY
CONTROL SELECTION
STRUCTURE
21

ONE WAY SELECTION


• Only involve an if statement (without else statement)
• If the condition is TRUE, the statement inside if.. will be
executed
• If condition is FALSE, the control goes to the next statement
placed outside the if statement (the if statement is ignored)
Condition is formed as
a Boolean expression
When condition is TRUE
expression statement

When condition is FALSE


22
EXAMPLE 3
Suppose the passing grade of a test is 50.

i. Draw a flowchart based on the program above


ii. If the marks is keyed-in as 50, what would be the output displayed on the screen?
iii. If the marks is keyed-in as 40, what would be the output displayed on the screen?
23
EXERCISE 3

i. Draw a flowchart based on the program above


ii. If the two integers entered are 15 and 9 respectively, what would
be the output displayed on the screen?
24
MAR 2014s PRACTICE 4

Answer: A
25

TYPES OF
SELECTION TWO WAY
CONTROL SELECTION
STRUCTURE
26

TWO WAY SELECTION


• Is used when a decision is required between two alternatives
• Uses if... else statement
• If the condition is TRUE, the statement inside if.. will be executed
and the statement inside else.. will be ignored
• If condition is FALSE, the statement inside if.. will be ignored and the
statement inside else.. will be executed
When condition is TRUE

expression

statement2 statement1
When condition is FALSE

Executed afterwards
27
EXAMPLE 4
i. Draw a flowchart based
on the program above

i. If the hoursWorked is
keyed-in as 50, what
would be the output
displayed on the screen?

ii. If the hoursWorked is


keyed-in as 100, what
would be the output
displayed on the screen?
28

JAN 2018 EXERCISE 4


PART B
QUESTION 3
29

JAN 2018
PART B QUESTION 3
EXERCISE 4
#include <iostream> OUTPUT ON SCREEN
using namespace std;
int main()
{
float price, total = 0;
int quantity = 0;
cout << "Please enter the quantity of magazines: ";
cin >> quantity;
if (quantity > 50)
price = 12.50;
else
price = 18.90;
total = quantity*price;
cout <<"The total price for " <<quantity <<" magazines is
RM"<<total;
return 0;
}
30

TYPES OF
SELECTION MULTIPLE
CONTROL SELECTION
STRUCTURE
31

MULTIPLE SELECTION
• Is used when there are multiple
conditions involved
• Can be implemented using any of the 3
ways:
i. Linear Nested if Statement
ii. Non-linear Nested if Statement
iii. switch Statement
32

NESTED IF STATEMENT
NESTED SELECTION (nested IF statement)
• A nested selection occurs when the word IF appears more than
once within an IF statement.
• A nested IF statements can be classified as linear or non-linear.
LINEAR NESTED IF statements NON-LINEAR NESTED IF statements
• The linear nested IF statement is used when a field is • A non-linear nested IF occurs when a number of
being tested for various values and a different action different conditions need to be satisfied before a
is to be taken for each value. particular action can occur.
• This form of nested IF is called linear, because each • It is termed non-linear because the ELSE statement
ELSE immediately follows the IF condition to which it may be separated from the IF statement with which it
corresponds. is paired
Transaction Code Action Condition 1 Condition 2 Action
A Add a new customer record Salaried Pay base salary
C Change customer record Employee
D Delete customer record Hourly Hours <= 40 Calculate pay at hourly
Any other code Display error message Employee rate
Hourly Hours > 40 Calculate pay with
Employee overtime
33

LINEAR
TYPES OF SELECTION CONTROL STRUCTURE

MULTIPLE NESTED
SELECTION if
STATEMENT
MULTIPLE SELECTION
34

LINEAR NESTED IF STATEMENT


• Is used when there are multiple conditions based on the same
subject
• Uses nested if.. else (one control statement inside another)
• The program will continuously check each condition starting from
the top to the bottom until it has found the condition that is TRUE
• Once the condition is evaluated as TRUE,
the statement inside if.. will be executed and the other if statements
will be ignored

• If there are no condition that can be evaluated as TRUE, the last


else.. statement will be executed (if exist)

Executed afterwards
35

EXAMPLE 5
i. Draw a flowchart based on the
program given →
ii. If the grade is keyed-in as B, what
would be the output displayed on the
screen?
iii. If the grade is keyed-in as E, what
would be the output displayed on the
screen?
36

SEP 2015 EXAMPLE 6


PART B QUESTION 2 (d)
37

SEP 2015 EXAMPLE 6


PART B QUESTION 2 (d)
#include <iostream>
using namespace std;
int main()
{
char code;
cout << "Select a seat code (B or E) ";
cin >> code;

if (code == "B" || code == 'b')


{
cout << "Business Class: RM120" <<endl;
}
else if (code == "E" || code == 'e')
{
cout << "Economy Class: RM80" <<endl;
}
else
{
cout << "Sorry. Invalid code" <<endl;
}
return 0;
}
38

MAR 2013 EXAMPLE 6.1


39

OCT 2010
PART B
QUESTION 3

EXERCISE 5
#include <iostream>
using namespace std;
40

OCT 2010 int main()


{
int destination, totalTicket = 0;
float destinationPrice, totalPrice = 0;
PART B cout << "\nPlease choose you destination ";
cout << "\nl. Kuala Lumpur to Kuala Terengganu";
QUESTION 3 cout << "\n2. Kuala Lumpur to Alor Setar ";
cout << "\n3. Kuala Lumpur to Kota Bahru ";
cout << "\n4. Kuala Lumpur to Butterworth";

EXERCISE 5 cout << "\n5. Kuala Lumpur to Johor Bahru" << endl;
cin >> destination;

cout << "\nPlease enter total ticket that you want to buy ";
cin >> totalTicket;
TO ANSWER THE QUESTION:
if (destination== 1)
destinationPrice = 54;
else if (destination== 2)
destinationPrice = 42;
else if (destination== 3)
destinationPrice = 64;
else if (destination== 4)
destinationPrice = 38;
else if (destination== 5)
ANSWER destinationPrice = 45;
c) i) The total price is RM 192 else
cout << "\nYou have made the wrong destination";
ii) The total price is RM 45
iii) You have made the wrong decision. totalPrice = totalTicket*destinationPrice;
cout << "\nThe total price is RM "<<totalPrice;
The total price is RM 0 return 0;
}
#include <iostream>
using namespace std;
41 int main()

OCT 2010 {
int destination, totalTicket = 0;
float destinationPrice, totalPrice = 0;
cout << "\nPlease choose you destination ";
PART B cout << "\nl. Kuala Lumpur to Kuala Terengganu";
cout << "\n2. Kuala Lumpur to Alor Setar ";
QUESTION 3 cout << "\n3. Kuala Lumpur to Kota Bahru ";
cout << "\n4. Kuala Lumpur to Butterworth";
cout << "\n5. Kuala Lumpur to Johor Bahru" << endl;
cin >> destination;

EXERCISE 5 if (destination== 1)
destinationPrice = 54;
else if (destination== 2)
destinationPrice = 42;
THE CORRECT FLOW: else if (destination== 3)
destinationPrice = 64;
else if (destination== 4)
destinationPrice = 38;
else if (destination== 5)
destinationPrice = 45;
else
cout << "\nYou have made the wrong destination";

if (destination <= 5)
{
cout << "\nPlease enter total ticket that you want to buy ";
cin >> totalTicket;
totalPrice = totalTicket*destinationPrice;
cout << "\nThe total price is RM "<<totalPrice;
}
cout << "\nThank you for using our service.";
return 0;
}
42

NON
LINEAR
TYPES OF SELECTION CONTROL STRUCTURE

MULTIPLE NESTED
SELECTION if
STATEMENT
MULTIPLE SELECTION
43
NON-LINEAR NESTED IF STATEMENT
• Is used when a particular condition
contains multiple conditions of the
same subject
• Uses nested if.. else (one control
statement inside another)
Each of these conditions
can only be evaluated if
the OUTER CONDITION
is true

Executed afterwards →
44

EXAMPLE 7
i. Draw a flowchart based on the
program given
ii. If the gender and age is keyed-in as
M and 12 respectively, what would
be the output displayed on the
screen?
iii. If the gender and age is keyed-in as
W and 36 respectively, what would
be the output displayed on the
screen?
45

PART A
EXERCISE 5
QUESTION 6
46
OCT 2016 PART A
QUESTION 7 EXERCISE 6

What would be the output


on screen if:

item = 15? 15
item = 35? 25
47
COMPARING NUMBER / CHAR
if (age >= 17)
cout << “Teenager.”;

if (num != 0) COMPARING
num++;
STRING OF
if (grade == ‘A’)
cout << “Congratulations!”; char
COMPARING STRING OF char???
if (name >= ??????)
48

COMPARING STRINGS
• To compare strings in C++:
• A predefined function strcmp() is used
strcmp(str1, str2);

Will compare string in variable,


str1 and string in variable, str2

Will check if the two strings are


the SAME
49

COMPARING STRINGS
Returns an integral value indicating the relationship between the strings:

RETURN
INDICATES
VALUE
the first character
that does not match
<0
has a lower value
in str1 than in str2
the contents of both
0
strings are equal
the first character
that does not match
>0
has a greater value
in str1 than in str2
50

COMPARING STRINGS
• If we store integer value (that represents decimal value in ASCII
code), it will display the matching CHARACTER in ASCII

Store integer value (instead of ‘A’)

Display matching CHARACTER (instead of 65)


51

EXAMPLE 8
i. Draw a flowchart based on the
given program

ii. If the gender is keyed-in as


“Female”, what would be the
output displayed on the screen?

iii. If the gender is keyed-in as


“Male”, what would be the
output displayed on the screen?
*CONCATENATE means → Link (things) together in a chain or series.
52

*CONCATENATE STRINGS
Appends (add something) to a copy of the source string to the destination
string destination source
EXAMPLE

strcat(str1, str2);
Will ADD string str2 into str1

OUTPUT ON SCREEN
53
MAR 2017 PRACTICE 5
PART A
QUESTION 9
54

TYPES OF SELECTION CONTROL STRUCTURE switch


MULTIPLE STATEMENT
SELECTION
MULTIPLE SELECTION
55

switch STATEMENT
• Is an alternative method that When break statement is
executed, it will EXIT the
can be used for multiple switch

selection instead of a nested


if.. else
• Can only be used for
comparing:
✓ Integer expression (int)
✓ Character char constant
(char)
Default case is optional, it acts
like an else statement
MULTIPLE SELECTION
56

switch STATEMENT
• switch statement for Integer Expression:
57
OCT 2016 PRACTICE 6
PART A
QUESTION 6
58
OCT 2016 EXAMPLE 9
PART B
QUESTION 3 (a)
59
OCT 2016 EXAMPLE 9
PART B
QUESTION 3 (a)
#include <iostream>
using namespace std;

int main()
{
char alphabet; //0.25m
cin >> alphabet; //0.5m
switch(alphabet)
{
case 'A': cout << alphabet << " is a vowel. Example: Apple";//0.75m
break;
case 'E': cout << alphabet << " is a vowel. Example: Elephant";//0.75m
break;
case 'I': cout << alphabet << " is a vowel. Example: Igloo";//0.75m
break;
case 'O': cout << alphabet << " is a vowel. Example: Octopus";//0.75m
break;
case 'U': cout << alphabet << " is a vowel. Example: Umbrella";//0.75m
break;
default: cout << alphabet << " is a consonant.";//1m
}
return 0;
}
60

SEP 2015 EXERCISE 7


PART B QUESTION 2 (d)
61

SEP 2015 EXERCISE 7


PART B QUESTION 2 (d)
#include <iostream>
using namespace std;

int main()
{
char code;
cout << "Select a seat code (B or E) ";
cin >> code;

switch(code)
{
case 'B':
case 'b': cout << "Business Class: RM120" <<endl;
break;
case 'E':
case 'e': cout << "Economy Class: RM80" <<endl;
break;
default:
cout << "Sorry. Invalid code" <<endl;
}
return 0;
}
62
MAR 2016 EXAMPLE 10
PART B
QUESTION 3 (a)

SUGGESTED ANSWER:
if (plant > 8) if (win == 5)
water = 3; points = points + 5;
63

JAN 2018 EXERCISE 8


64

JAN 2018 EXERCISE 8


#include <iostream>
using namespace std;

int main()
{
char letter;
cout << "Please enter only ONE character: ";
cin >> letter;
switch(letter)
{
case 'A':
case 'B': cout << "Uppercase Letter";
break;
case 'a':
case 'b': cout << "Lowercase Letter";
break;
default: cout << "Incorrect Input";
}
return 0;
}
65
MAR 2016
PART B
QUESTION 3 (b)

EXAMPLE 9
#include <iostream>
#include <cmath>
66
MAR 2016 using namespace std;
int main()
PART B {
int num1, num2, result;
QUESTION 3 (b) char choice;
cout << "Enter choice (A or B): ";
EXAMPLE 9 cin >> choice; //0.5M
cout << "Enter two integer numbers: ";
cin >> num1 >> num2; //0.5M
switch(choice) //0.5M
{
case 'A':
case 'a': result = pow(num1, num2);
break;
case 'B':
case 'b’: result = sqrt(num1 * num2);
break;
default:
cout << "Wrong choice" <<endl;
}
cout << result;
return 0;
}
67
OCT 2016
PART B
QUESTION 3 (b)

EXERCISE 9

HINT:if……else
68
TYPES OF SELECTION CONTROL
STRUCTURE
ONE WAY SELECTION TWO WAY SELECTION
if (age > 17) if (age > 17)
{
cout << "You can vote.";
{
} cout << "You can vote.";
if (strcmp (nationality, “Malaysia”) == 0)
}
{
cout << "You can vote."; else
} {
cout << "You can't vote.";
}
Will check for each of the IF condition If the first condition is NOT MET, then,
it will fell for the second condition by default
69
TYPES OF SELECTION CONTROL
STRUCTURE (MULTIPLE SELECTION)
LINEAR NESTED IF NON-LINEAR NESTED SWITCH STATEMENT
STATEMENT IF STATEMENT
70

MAR 2013 EXERCISE 10


71

TOPIC 3
SELECTION CONTROL STRUCTURE
✓ control structures
✓ relational and logical
operators
✓ how to form and evaluate
logical (Boolean) expressions
✓ how to use the selection
control structures if, if...else in
a program
COMPLETE
72
REFERENCES

• Malik, D.S (2010). “C++ Programming: From Problem


Analysis to Program Design”. Cengage Learning
• Najwa Abd Ghafar. (2018). CSC128: Chap 3 – Selection Control
Structure [PowerPoint slides in PDF].
• Operators. Retrieved at
http://www.cplusplus.com/doc/tutorial/operators/
• Function strcmp. Retrieved at
http://www.cplusplus.com/reference/cstring/strcmp/
• Function strcat. Retrieved at
http://www.cplusplus.com/reference/cstring/strcat/

You might also like