Sei sulla pagina 1di 57

Chapter 4

Selection Control
Structures
Problem Concept

Learning Outcomes

Learning Outcomes
Apply selection control structure (simple
selection, multiple selection, and nested selection)

algorithms
Apply case construct in pseudocode
Recognize algorithms using variations of

selection control structure


Understand the basic concept of function
Construct a program with self-defined

function.

in

Introduction

Introduction
Define the following:
Decision Making
Subject
One or more Outcomes

Selection Control
Structure
IF-ELSE Selection
Switch Case Selection

Part One: IF-ELSE


Selection Control
Structure

Selection Control
Structure
You can use the selection control structure in

pseudocode to illustrate a choice between two or more


actions, depending on whether a condition is true or
false
The condition in the IF statement is based on a

comparison of two items, and is usually expressed with


one of the following relational operators:
< less than
> greater than
== equality
<= less than or equal to
>= greater than or equal to != not equal to
&& AND
|| OR
! NOT

Lets start from scratch


Let say were talking about where to have our

drinks after lecture


We could write something like this,
IF Im Rich THEN
Go to Starbucks
ELSE
Go to roadside mamak stalls
ENDIF
9

Keywords

(6 Basic Computer
Operations)

Condition

IF Im Rich THEN
Outcome(s)
Go to Starbucks
ELSE
Go to roadside mamak stalls
ENDIF
10

IF money >= 1000000 THEN


Display Millionaire!!
ELSE
Display Pooooor Guy
ENDIF
11

IF status == Y THEN
Display Yes!!
ELSE
Display No!!
ENDIF

12

Wait wait
Whats the difference between = and == ?
=
Assignment Operator
==
Comparison Operator

13

Part Two: More on


IF-ELSE Selection
Five types of IF-ELSE Selection

14

5 IF-ELSE Selections
1.
2.
3.
4.
5.

Simple Selection
Simple Selection (with null ELSE)
Combine Selection (AND, OR)
NOT Selection
Nested Selection
Linear (IF followed by ELSE)
Non-linear (Mixed e.g. IF followed by another

IF)

15

1. Simple Selection (Simple IF


Statement)
Simple selection occurs when a choice is made

between two alternate paths, depending on the


result of a condition being true or false
The structure is represented in pseudocode using

the keywords IF, THEN, ELSE, and ENDIF


Only one of the THEN or ELSE paths will be

followed, depending on the result of the condition


in the IF clause

16

2. Simple Selection with Null False


Branch (Null ELSE Statement)
The null ELSE structure is a variation of the

simple IF structure
It is used when a task is performed only when

a particular condition is true


If the condition is false, then no processing

will take place and the IF statement will be


bypassed

17

3. Combined Selection (Combined


IF Statement)
A combined IF statement is one that contains

multiple conditions, each connected with the


logical operators AND or OR

If the connector AND is used to combine the

conditions, then both conditions must be true for


the combined condition to be true

If the connector OR is used to combine any two

conditions, then only one of the conditions needs


to be true for the combined condition to be
considered true
18

4. The NOT Operator


The NOT operator can be used for the logical

negation of a condition, as follows:


IF NOT (record_code = =23) THEN
update customer record
ENDIF

Note that the AND and OR operators can also be

used with the NOT operator, but great care must


be taken and parentheses should be used to avoid
ambiguity as illustrated on page 38 of the
textbook
19

5. Nested Selection (Nested IF


Statement)
Nested selection occurs when the word IF

appears more than once within an IF statement


Nested IF statements can be classified as
A. Linear
B. non-linear

20

5 (A). Linear Nested IF Statements


The linear nested IF statement is used when a

field is being tested for various values and a


different action is to be taken for each value
This form of nested IF is called linear, because

each ELSE immediately follows the IF condition to


which it corresponds

21

5 (B). Non-Linear Nested IF


Statements
A non-linear nested IF occurs when a number of

different conditions need to be satisfied before a


particular action can occur
It is termed non-linear because the ELSE

statement may be separated from the IF


statement with which it is paired

22

Linear Nested IF
IF marks >= 80 THEN
Display Grade is A
ELSE
IF marks >= 75 THEN
Display Grade is A-
ELSE
IF marks >= 70 THEN
Display Grade is B+
ENDIF
ENDIF
ENDIF

Simple Selection

Simple Selection

Simple Selection
with null ELSE

23

Non-Linear Nested IF
IF marks >= 40 THEN
IF marks >= 75 THEN
IF marks >= 80 THEN
Display Grade is A
ELSE
Display Grade is A-
ENDIF
ELSE
Display Grade is B+ or less
ENDIF
ENDIF

Simple Selection

Simple Selection

Simple Selection
with null ELSE

24

Example
An electric power distribution company charges its

domestic consumers as follows:


Consumption Rate of charges
0 200
RM0.50 per Unit
201 400

RM1.00 plus RM 0.65 per unit excess 0f

200
401 600 RM2.30 plus RM 0.80 per unit excess 0f
400
601 and above
RM3.90 plus RM 1.00 per unit
excess 0f 600

This program reads the customer number and


25
power consumed and prints the amount to be
paid

Part Three: Switch


Case Structure

Something to know first

Limitations
Variable limited to int and char
Value checked valid for singled-value

instead of ranged-value.

27

The Case Structure


The case control structure in pseudocode is

another way of expressing a linear nested IF


statement

It is used in pseudocode for two reasons: it can be

directly translated into many high-level


languages, and it makes the pseudocode easier to
write and understand

Nested IFs often look cumbersome in pseudocode

and depend on correct structure and indentation


for readability
28

How do we write?
CASEOF number
1: Display Number 1
2: Display Number 2
other: Display Other than 1 and 2
ENDCASE

29

How do we write? (cont.)


CASEOF gender
M: Display Male
F: Display Female
other: Display Huh??
ENDCASE

30

Exercises

31

Extra Question 1
Kuala Lumpur sometimes has very hazy conditions,
and raise health concern among the residence. A
pollutant hazard index has been developed. If the
index rises above 100, the air is listed as
unhealthful. If the index rises above 200, a
first-stage haze alert is issued and certain
activities are restricted. If an index goes over 275,
a second-stage alert is called and more severe
restrictions apply. Write a program that takes an
input the daily hazard index and identifies the
alert situation.
32

Extra Question 2
Write a program that reads an employees
number, hours worked, and hourly rate and
calculates his or her wages. All hours over 40
are paid at 1.5 times the regular hourly rate.

33

Extra Question 3
Design a solution print a letter grade given
and examination score.
Grades and marks
A 4-point grading system is adopted:

Grade
Marks Range Grade Point
Description
A
80 -100 4.00
Excellent
A75 -79
3.70
Excellent
B+
70 -74
3.30
Very Good
B
65 -69
3.00
Good
B60 -64
2.70
Good
C+
55 -59
2.30
Satisfactory
C
50 -54
2.00
Pass
D
40 -49
1.00
Passing
F
0 -39
0.00
Fail

Extra Question 4
Design a solution to calculate the water bill given the cubic
meter of water used for PUAS Water Company, which charges
the homeowner one of the following:
A. A flat rate of RM10.00 for usage up to and including 100
cubic meter.
B. $0.20 per cubic meter for usage over 100 cubic meter and
up to and including 200 cubic meter.
C. $0.35 per cubic meter for usage over 200 cubic meter

Extra Question 5
A customer needs a specific amount of paper. The
charges on the paper are RM0.10 for single sheets,
RM0.07 for amounts in multiples of 100 sheets,
RM0.05 in multiples of 500 sheets, and RM0.03 in
multiples of 1000 sheets.
Develop a solution to calculate the type and
number of package(s) for the least amount of
money the customer should buy. given the
minimum amount of sheets the customer needs.
For example, if the customer needs 380 sheets, the amount
she would pay when buying in multiples of 100 would be 36

Extra Question 6
A hotel has a pricing policy as follows:
a.
b.
c.
d.

2 people: RM85
3 people: RM90
4 people: RM95
Additional people: RM25 per person

If the customer is staying on company business,


there is a 20% discount. If the customer is over 60
years of age, there is a 15% discount. A customer
does not receive both discounts. Given the above
data, print the cost of the room.
37

Function
Self - defined function

Defining function
A function have 2 main components
1.Function header(function declaration)
2.Function body (functions program codes)

General structure for function definition:


1. return data type
function name
2.{
functions program codes
return expression
}

(arguments)

Function definition
1.Function header
return data type

data type of the value that is returned by the function to the


program which called the function
function name

the name given to this function


Arguments (data_type arg1 , data_type2 arg2)

the data needed by the function to perform its task,


arguments are separate by commas, if no arguments are
needed, empty parentheses is used.

Function definition
2.Function body
The body contain all the program codes that

specifies the action to be taken by the function


return statement
to return a value to the portion of program which called
the function. If no value are to be return, expression is
omitted
(return ; or return 0;)

Function definition
(example)
int

add (int number1 , int number 2)

{
int total = 0;
total = number1 + number2;
return (total);
}
In the above example, it is a simple function named add.
The add function will receive 2 integer type data
(arguments) from the program, it will add them up and
pass the integer data total (return data type is int)
back to the program which called the function using the
return statement.

Accessing a function
A function can be accessed (called) by specifying

its name, follow by list of arguments enclosed in


parentheses and separated by commas, if the
function call does not required arguments, empty
parentheses is used.
If the function return a value, the function access

is often written as an assignment statement:


variable name = function name (arguments);

If the function does not return anything. The

function access appears by itself:


function name (arguments);

Accessing a function
(example)
In the previous example, we created an add

function that add two numbers, since this function


is going to return an integer value (total), in order
to access the function, following codes are
needed:
total = add (number1, number2);

Program Structure

Basic Program Structure


Preprocessor Commands
Global Declaration
int
{
}

main
(void)
Local Declaration
Statements

Basic Program Structure


Preprocessor Command
Come at the beginning of the program.
All commands start with a pound sign (#)
Tells the compiler to include the library needed
by the program
Library contains a lot of predefined function
that can help us to perform tasks
#include <stdio.h>
(used to include the standard input/output
library file so that we can use printf and scanf
function)

Basic Program Structure


Global declaration
Variables declare at this section is visible to all
parts of the programs.
Local declaration
Variables that declare in a certain function.
Visible only to the function contain them.
Statement
The actions to be performed by the function.

Basic Program Structure


(example)
#include <stdio.h>
int main (void)
{
int total = 0; number1 = 0; number2 = 0;
printf(\nPlease enter first number \n>);
scanf(%d,&number1);
printf(\nPlease enter second number \n>);
scanf(%d,&number2);
total = number1 + number2;
printf(the total is : %d,total);
return 0;
}

Program Structure(with Self-defined


function)
Preprocessor Commands
Function Prototypes
Global Declaration
int
{

main
(void)
Local Declaration
Statements

}
Self-defined function

Program Structure(with Self-defined


function)
Normally when we use functions in a program, we will

follow the top-down approach where the additional


function (programmer defined functions) are written
after the main function.
Since the compiler will compile the codes starting from

the upmost line until the bottom, we need to tell the


compiler, what are the functions included in the
program beside the main function, and this can be
done by using function prototype.

Function prototypes
Function prototypes are line of codes use to inform the

compiler regarding the additional functions beside main


function.
return data type

function name

(argument );

return data type

data type of the value that is returned by the


function
function name
Name of the function
argument
Arguments that are required by the functions

Function prototypes
(example)
The function prototype looks similar to the

function definition but ends with a semicolon.


In our previous example we have created an add

function, following is the function prototype for


the add function:
int

add (int number1 , int number2);

Program Structure
(example)
#include <stdio.h>
int add (int number1, int number2); // function prototype
int main (void)
{
int total = 0; number1 = 0; number2 = 0;
printf(\nPlease enter first number \n>);
scanf(%d,&number1);
printf(\nPlease enter second number \n>);
scanf(%d,&number2);

total = add (number1, number2);


printf(the total is : %d,total);
return 0;

Program Structure (example


continued)
int add (int number1 , int number 2)
{
int total = 0;
total = number1 + number2;
return (total);
}

Summary

56

Summary
This chapter covered the selection control

structure in detail
Descriptions and pseudocode examples were

given for simple selection, null ELSE, combined IF,


and nested IF statements
The case structure was introduced as a means

of expressing a linear nested IF statement in a


simpler and more concise form
57