Download as pdf or txt
Download as pdf or txt
You are on page 1of 105

SECTION 2

TUTORI AL
" Teachers open the
door but you must
walk through it
yourself "

C HI NE S E P R OV E R B
Table of Contents
CHAPTER 1 PROBLEM SOLVING ............................................................................................... 1
1.1 Introduction ........................................................................................................................ 1
1.2 Steps in Problem Solving ...................................................................................................... 1
1.2.1 Step 1: Problem Analysis ................................................................................................................... 2
1.2.2 Step 2: Design a Solution ................................................................................................................... 3
1.2.3 Step 3: Implementation ....................................................................................................................... 3
1.2.4 Step 4: Testing and Verification ........................................................................................................ 3
1.2.5 Step 5: Documentation ....................................................................................................................... 3
1.3 Algorithms ........................................................................................................................... 4
1.3.1 Pseudocodes ....................................................................................................................................... 5
1.3.2 Flowcharts ............................................................................................................................................ 7
Tutorial 1 (Problem Solving) ............................................................................................................ 9
Enrichment Questions ................................................................................................................... 11
CHAPTER 2 SEQUENCE CONTROL STRUCTURES ...................................................................... 12
2.1 Introduction ...................................................................................................................... 12
Tutorial 2 (Sequence) .................................................................................................................... 26
Enrichment Questions ................................................................................................................... 29
CHAPTER 3 SINGLE SELECTION CONTROL STRUCTURES .......................................................... 32
3.1 Introduction ...................................................................................................................... 32
Tutorial 3 (Single Selection) ........................................................................................................... 35
Enrichment Questions ................................................................................................................... 38
CHAPTER 4 DUAL SELECTION CONTROL STRUCTURES ............................................................ 39
4.1 Introduction ...................................................................................................................... 39
Tutorial 4 (Dual Selection) ............................................................................................................. 48
Enrichment Questions ................................................................................................................... 51
CHAPTER 5 MULTIPLE SELECTION CONTROL STRUCTURES ...................................................... 54
5.1 Introduction ...................................................................................................................... 54
Tutorial 5 (Multiple Selection) ....................................................................................................... 63
Enrichment Questions ................................................................................................................... 66
CHAPTER 6 REPETITION CONTROL STRUCTURES COUNTER-CONTROLLED .............................. 71
6.1 Introduction ...................................................................................................................... 71
Tutorial 6 (Counter-controlled Repetition) ..................................................................................... 85
Enrichment Questions ................................................................................................................... 88
CHAPTER 7 REPETITION CONTROL STRUCTURES SENTINEL-CONTROLLED ............................... 89
7.1 Introduction ...................................................................................................................... 89
Tutorial 7 (Sentinel-controlled Repetition) ..................................................................................... 98
Enrichment Questions ................................................................................................................. 101
APPENDIX A – ANSWER SHEET ............................................................................................ 102
CHAPTER 1
PROBLEM SOLVING
Learning Objectives
In this chapter, you will learn about:
(a) What problem solving is, and
(b) Five (5) steps in the software development method:
(i) Problem Analysis
(ii) Design a Solution
(iii) Implementation
(iv) Testing
(v) Documentation

1.1 Introduction
Problem solving is the process of transforming the description of a problem into a solution by
using our knowledge of the problem domain and by relying on our ability to select and use
appropriate problem-solving strategies, techniques and tools (Yuksel Uckan, 1995).

1.2 Steps in Problem Solving


Five (5) steps in problem solving:
• Step 1: Problem Analysis
• Step 2: Design a Solution
• Step 3: Implementation
• Step 4: Testing
• Step 5: Documentation

Page 1
1.2.1 Step 1: Problem Analysis
In problem analysis step, we should identify the following:
• Input
• Process
• Output

This problem analysis can be represented by the Input-Process-Output (IPO) chart as


follows:
required data to the problem
Input :
– usually entered by user using keyboard
relevant action(verb) / condition (if any) involved to produce output
Process : from input
– involve calculation/selection/repetition
expected result after processed
Output :
– to be displayed on the monitor

Example of Problem Analysis

Problem Statement:
Calculate the sum of any two numbers.
Input : num1, num2

Process : Calculate sum for num1, num2

Output : Sum

Here, num1, num2 are input, data required for the problem to be solved. Usually the value
for input (num1, num2) are entered by user through keyboard.

The verb Calculate is used to represent the process. The process reflects to the problem
statement or question.

The sum is the output, i.e expected result after process. The value for output (sum) will be
printed/displayed on the computer monitor.
*(This step will be discussed in detail in Chapter 2 Control Structures.)

Page 2
1.2.2 Step 2: Design a Solution
• Design a solution involves creating an algorithm.
• An algorithm is a sequence of well-defined steps to solve a problem.
• We specify a plan that will solve the problem and elaborate the plan into step by step
solution (algorithm).
• Algorithm can be represented using pseudocodes or flowcharts.

*(This step will be discussed in detail in subtopic 1.3 Algorithms)

1.2.3 Step 3: Implementation


• Implementation is the process of implementing an algorithm by writing a computer
program such as Scratch program.

1.2.4 Step 4: Testing and Verification


• After a program is compiled, we must run the program and verify it with different
inputs.
• In this phase, your main objective is to convince that the program will do what it is
expected to do. In other words, you will want to verify that your program is correct.
• Program verification is the process of ensuring that a program meets user-requirement
(i.e. test/verify it with different inputs).
• One of the techniques used for program verification is program testing. Program testing
is the process of executing a program to demonstrate its correctness (i.e. run the
program).

1.2.5 Step 5: Documentation


• Documentation contains description of the program that helps other programmers in
editing or maintaining the program later.
• Can be done in 2 ways:
o Writing comments between your lines of codes
o Creating a separate text file to explain the program

Page 3
1.3 Algorithms
The second (2nd) step 2 in solving a problem is design a solution. Design a solution involves
creating an algorithm. In order to instruct a computer correctly, the user must have clear
understanding of the problem to be solved. Apart from this he should be able to develop an
algorithm, in the form of series of sequential steps, to solve it. Once the problem is well-
defined and a method of solving it is developed, then instructing the computer to solve the
problem becomes relatively easier task.

Thus, before attempt to write a computer program to solve a given problem, it is necessary to
formulate or define the problem in a precise manner using algorithm.
An algorithm is a well-defined procedure that allows a computer to solve a problem. It
shows step-by-step instruction that will transform the input into the output. The algorithm
will be created based on the problem analysis prepared earlier.

There are two (2) techniques to represent algorithm:

• Pseudocode
• Flowchart

Page 4
1.3.1 Pseudocodes
A pseudocode is a semiformal, English-like language with a limited vocabulary that can be
used to design and describe algorithms.

The main purpose of a pseudocode is to define the procedural logic of an algorithm in a simple,
easy-to-understand for its readers, who may not be proficient in computer programming
language.

In writing a pseudocode, one should start by doing problem analysis for the problemstatement
(i.e: identify input, process, and output).

Problem Analysis Pseudocode Format

Begin
Input : data Input / Read / Get data
Process : action Formula
Output : result Output/Print/Display result
End

Here, the Pseudocode Format will take all the information from the Problem Analysis into
it’s format respectively.
In pseudocode, the Input will be represented by the keyword Input itself, or can be
represented using the keyword Read or Get.
For Process, it will converted into its respective formula.
For Output, it will be represented by the keyword Output itself, or can be represented using
the keyword Print or Display.

In short, we can conclude that:


Input = Read = Get data
Process → Formula
Output = Print = Display result

*In this book, this keyword (input/output) will be used alternately.

Page 5
Example Pseudocode 1: A Pseudocode that Calculate the Sum of any Two
Numbers

Problem Analysis Pseudocode Format

Begin
Input : num1, num2
Read num1, num2
Process : Calculate sum based on
sum = num1 + num2
num1, num2
Print sum
Output : sum
End

Here, in the Problem Analysis, the process part will be formulated into it’s respective
equation. For example,

Process : Calculate sum sum = num1 + num2

Example Pseudocode 2: A Pseudocode that Calculate the Sum and Average of any
Three Numbers

Problem Analysis Pseudocode Format

Begin
Input : num1, num2, num3
Read num1, num2, num3sum
Calculate sum and
= num1 + num2 + num3
Process : average based on num1,
average = sum / 3
num2, num3
Print sum, average
Output : sum, average
End

Page 6
1.3.2 Flowcharts
A flowchart is a graphical representation that are connected by arrows to represent algorithm.

It is easy to understand type and flow of instruction in graphical representation.


Graphic Symbols Name Meaning
Indicates the beginning and end
points of an algorithm.
Terminal Symbol
(Shape: Oval) There should be no more than two
terminal symbols in a flowchart for
an algorithm.
shows an input or an output
Input-Output operation.
Symbol
(Shape: Each such symbol should contain
Parallelogram) the keyword read or print, and what
is to be read or to be printed.
Shows an operation other than input,
output or selection.
Process Symbol
They represent operations such as
(Shape: Rectangle)
computations, assignments, and
initialization.

indicates the logical sequence of


Flow Lines
execution steps in the algorithm
shows a selection process.

Selection Symbol It stands for the keyword if in


(Shape: Diamond) pseudocode. The if condition should
be written inside the selection
symbol.
Figure 1.1 Conventional flowcharting symbols

It is recommended to draw a flowchart after you created a pseudocode. This because once the
pseudocode is complete, then give its appropriate shape connected by arrows, it will become
a flowchart.

Page 7
Example Flowchart 1.1: A Flowchart that Calculate the Sum of any Two Numbers
Pseudocode Flowchart

Begin
Begin

Read num1, num2


Input num1, num2

sum = num1 + num2


sum = num1 + num2

Print sum
Output sum

End End

Example Flowchart 1.2: A Flowchart that Calculate the Sum and Average of any
Three Numbers
Pseudocode Flowchart

Begin
Begin

Read num1, num2, Read num1, num2,


num3 num3

sum = num1 + num2 + num3


sum=num1+num2+num3 average = sum / 3
average = sum / 3

Print sum, average Print sum, average

End End

Page 8
Tutorial 1 (Problem Solving)

1 Define algorithm.
______________________________________________________________________
______________________________________________________________________

2 State one (1) technique that used to represent algorithm.


______________________________________________________________________

3 Describe one advantages of the technique that you have mentioned above.
______________________________________________________________________
______________________________________________________________________

4 List the first two (2) steps in problem solving.


______________________________________________________________________
______________________________________________________________________

5 Explain any one (1) step mentioned in question 4.


______________________________________________________________________
______________________________________________________________________

6 Differentiate between pseudocode and flowchart.


______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

7 Create problem analysis for the following problems:

(a) Calculate the sum of two integers.

Page 9
(b) Find the average of three numbers.

(c) Calculate the area of a circle.

(d) Convert a measurement in millimeter (mm) to meter (m).

(e) Calculate the Body Mass Index (BMI) for a person.

Page 10
Enrichment Questions

(f) Calculate and display the overtime pay received by an employee. Overtime
rate is RM5 per hour.

(g) Calculate and print the surface area and volume of a sphere.

(h) Calculate the final mark for a student; where the final mark will be calculated
by adding 30% of the test mark with 70% of the lab mark.

(i) Calculate the sale price of a shirt given that the shirt is on sale at 30%
discount.

(j) Create a program to convert the temperature value in Fahrenheit (F) to degrees
Celcius (C) given the formula F = 9/5C + 32.

* Student can write the answer using example answer sheet at Appendix A

Page 11
CHAPTER 2
SEQUENCE CONTROL STRUCTURES
Learning Objectives
In this chapter, you will learn about:
a) Sequence control structure and its’ respective purposes, and
b) Applying sequence control structures in computational problem solving.

2.1 Introduction
In 1966, two researchers, Bohm and Jacopini, demonstrated that any algorithm can be
described using only three control structures:

• sequence,
• selection, and
• repetition.

Therefore, a pseudocode must have constructs that correspond to these control structures in
its vocabulary.

A control structure is a block of programming that analyses variables and chooses a direction
in which to go based on given parameters. It shows the logical order of program instructions.

Therefore, there are three (3) types of programming language control structures:

• Sequence Control Structures


• Selection Control Structures
• Repetition Control Structures

Page 12
The sequence control structure is a series of actions that are sequentially executed in the
order they are written in an algorithm. All actions will be executed sequentially. Actions can
be input, process, or output.

Pseudocode General Format Flowchart General Format


Begin
action1
action2
action3 action1

… action2

action nth
End action3

*Actions (action1, action2, action3, …, action-nth) can be input, process, or output.


Pseudocode Code Blocks

Begin / Start

action (Input)

action (Process)

action (Output)

End / Stop

Table above shows the representation of pseudocode using the Scratch software.
SCRATCH is a programming language that lets you create your own interactive stories,
animations, games, music, and art.

Page 13
Problem Statement 1.1:
Print "Hello, world!".

Problem Analysis
Input : No input
Process : No process
Output : "Hello, world!"

Here, in this problem statement, it does not have any data (input) to be manipulated
(process) to produce the output. It only requires output statement to print the
message "Hello, world!".

Algorithm (Pseudocode)
Begin
Print "Hello, world!"
End
In pseudocode, Output in problem analysis is represented by the keyword Output
itself, or can be represented by the keyword Print or Display.

Algorithm (Flowchart)

Begin

Print "Hello, world!"

End

In flowchart, Begin (or Start) and End is placed into a terminal shape. The
keyword
Output/Print/Display is placed in a parallelogram shape.

Page 14
Pseudocode Scratch Code

Begin

Print "Hello, world!"

End

The representation of keyword in pseudocode using Scratch code (block).

A Complete Scratch Program

Page 15
Problem Statement 1.2:
Calculate and print the square of a number.

Problem Analysis
Input : num
Process : Calculate square based on num
Output : square

Algorithm (Pseudocode)
Begin
Read num
square = num x num
Print square
End

Algorithm (Flowchart)

Begin

Read num

square = num x num

Print square

End

Page 16
Pseudocode Scratch Code

Begin

Read num

square = num x num

Print square

End

A Complete Scratch Program

Page 17
Problem Statement 1.3:
Calculate and print the sum of any two numbers.

Problem Analysis
Input : num1, num2
Process : Calculate sum based on num1, num2
Output : sum

Algorithm (Pseudocode)
Begin
Read num1, num2
sum = num1 + num2
Print sum
End

Algorithm (Flowchart)

Begin

Read num1, num2

sum = num1 + num2

Print sum

End

Page 18
Problem Statement 1.4:
Calculate and print the sum and average of any three numbers.

Problem Analysis
Input : num1, num2, num3
Process : Calculate sum and average based on num1, num2, num3
Output : sum, average

Algorithm (Pseudocode)
Begin
Read num1, num2, num3
sum = num1 + num2 + num3
average = sum / 3
Print sum, average
End

Algorithm (Flowchart)

Begin

Read num1, num2, num3

sum = num1 + num2 + num3


average = sum / 3

Print sum, average

End

Page 19
Problem Statement 1.5:
Calculate and print the square and square root of a number.

Problem Analysis
Input : number
Process : Calculate the square and square root based on number
Output : square, square root

Algorithm (Pseudocode)
Begin
Read number
square = number2
square root = √number
Print square, square root
End

Algorithm (Flowchart)

Begin

Read number

square = number2
square root = = √number

Print square, square root

End

Page 20
Problem Statement 1.6:
Calculate and print the area of a triangle.

Problem Analysis
Input : base, height
Process : Calculate area based on base, height
Output : area

Algorithm (Pseudocode)
Begin
Read base, height
area = 0.5 x base x height
Print area
End

Algorithm (Flowchart)

Begin

Read base, height

area = 0.5 x base x height

Print area

End

Page 21
Problem Statement 1.7:
Calculate and print the perimeter and area of a rectangle.

Problem Analysis
Input : length, width
Process : Calculate perimeter and area based on length, width
Output : perimeter, area

Algorithm (Pseudocode)
Begin
Read length, width
perimeter = 2(length + width)
area = length x width
Print perimeter, area
End

Algorithm (Flowchart)

Begin

Read length, width

perimeter = 2(length + width)


area = length x width

Print perimeter, area

End

Page 22
Problem Statement 1.8:
Calculate the pay price of an item after 25% discount.

Problem Analysis
Input : original price
Process : Calculate the pay price based on original price
Output : pay price

Algorithm (Pseudocode)
Begin
Read original price
pay price = 75% x original price
Print pay price
End

Algorithm (Flowchart)

Begin

Read original price

pay price = 75% x original price

Print pay price

End

Page 23
Problem Statement 1.9:
Calculate the pay price of a meal after 6% sales tax.

Problem Analysis
Input : meal price
Process : Calculate the pay price based on meal price
Output : pay price

Algorithm (Pseudocode)
Begin
Read meal price
pay price = 106% x meal price
Print pay price
End

Algorithm (Flowchart)

Begin

Read meal price

pay price = 106% x meal price

Print pay price

End

Page 24
Problem Statement 1.10:
Calculate and print the electric bill for the given usage in kWh and rate (sen/kWh).

Problem Analysis
Input : usage, rate
Process : Calculate electric bill based on usage, rate
Output : electric bill

Algorithm (Pseudocode)
Begin
Read usage, rate
Calculate electric bill
Print electric bill
End

Algorithm (Flowchart)

Begin

Read usage, rate

bill = usage x rate

Print bill

End

Page 25
Tutorial 2 (Sequence)
Write the problem analysis, pseudocode and flowchart for each question

1 A Computer Science lecturer wishes to determine the carry marks for every student.
The carry marks is taken from the average marks of three practical tests and the total
marks of two written assignments. Print the carry marks for a student.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 26
2 A factory worker is paid based on the total working hours of RM 5.50 per hour. 11%
of the total salary will be deducted for contribution to KWSP. Prepare the monthly
net salary of the factory worker.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 27
3 Convert the weight from kilogram to pound. (Formula: Weight in pound = weight in
kilogram x 2.2)
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 28
Enrichment Questions

4 A car travels from station A to station B. Calculate the distance from station A to station
B. (distance = speed x time)

5 Calculate and display four mathematical calculations; addition, multiplication,


subtraction and division for two numbers.

6 A government tax of 6% and service tax of 10% will be added to the price of a set of
meal bought at MFC. Calculate the total price that Abu has to pay for a set of meal.

7 Create a program to calculate the delivery cost of a package where the delivery cost per
kilogram is RM5.00.

8 User will enter his/her name and birth year. The program will calculate the user’s age
12 years after. Then, display the user’s name and new age.

9 Seri Murni holdings will distribute yearly dividend to all their shareholders. The
dividend is 15% from the total investment. Quarter amount from the dividend will be
deducted automatically to Sport’s Club. Calculate and display the remaining value of
the dividend.

10 Manees Store sells sugar, flour and egg. Calculate the total price of items purchased
from the store. The price of each item is shown as below:
(a) Sugar is sell for RM2.40 per kilogram
(b) Flour is sell for RM2.00 per packet
(c) Egg is sell for RM0.50 per piece.

11 A GST tax of 6% and delivery charge of RM50 has been charged to an electronic
product bought at Savory Shop. Calculate the total price of an electronic product that
customer should pay.

Page 29
12 A hotel wants an application to calculate the bill for a guest. Guests are charged based
on night stayed and nightly rate. They are also charged for room service and phone use.
Display the total bill for the guests.

13 Seri wants to do some home renovations so she takes a one year loan at the rate of
3.21%. Calculate and display the interest that she should pay for the loan.

14 An employee will be given a yearly bonus which is 10% of his annual salary. Given
that his monthly salary is RM400. Calculate the employee’s net yearly income.

15 Mr. Yamani is a barber. He takes 10 minutes to complete a haircut for one customer.
Calculate the total customers that he can entertain based on his total working hours.

16 Aziz want to create a program to calculate the shaded area below:


Y cm

X cm

Z cm Z cm
17 Calculate the total salary for a worker. A worker will be paid RM3.50 per hour. 11%
from total salary will be contributed to KWSP and RM10 will be deducted to
PERKESO.

18 Zamani wants to create a program that will calculate and display the total perimeter of
a rectangle and 2 different squares.

19 Mat Chicken is a restaurant that sells various foods for its customer. 6% of sales and
service tax (SST) will be added on the top of customer’s bill. Another 5% of service
charge is also will be added in the bill. Calculate and display the total bills of the
customer.

20 Calculate the total price of fruits based on the table below:


Fruits Price
Rambutan RM 3.50/kg
Mangoesteen RM 4.00/kg
Watermelon RM 1.00/kg

Page 30
21 Maju Holdings wants to buy a piece of land for their new development project. The
land is in rectangular shape. If the land is selling for RM7.50/m2, calculate the total
price of land.

22 A program will display user’s name and gender, based on the input entered.

23 Moonlight Insurance Sdn. Bhd. is an insurance company. Based on their policy, 10%
from the fees will be covered for medical card, 70% is for saving and the rest will be
refund back to the customer. Calculate the refund amount that a customer will get if
he had invested RM150 per month after 3 years.

24 The ticket price for riding the Eyes-On-Malaysia is RM4 for an adult and a child is
charge half of it. Calculate the total charge of the problem above.

25 User will insert an integer. Calculate the total, the multiplication and the power of the
integer if all operations is performing by using the integer itself.

26 A program will accept two integers from a user. Then the program will calculate the
sum and the difference of these two numbers.

* Student can write the answer using example answer sheet at Appendix A

Page 31
CHAPTER 3
SINGLE SELECTION CONTROL STRUCTURES
Learning Objectives
In this chapter, you will learn about:
a) Single selection control structure and its’ respective purposes, and
b) Applying single selection control structures in computational problem solving.

3.1 Introduction
Checks a condition to perform action(s).
If condition is true (T), perform action(s)
If condition is false (F), skips it (i.e. perform nothing – null)

Pseudocode General
Flowchart General Format
Format

if condition
T
action(s) action(s)
condition
endif
F

*endif is used to indicate end of if block.


Pseudocode Code Blocks

if condition
action(s)
endif

Page 32
Problem Statement 1.1:
Calculate and print the area of a circle if the radius is not a negative value.

Problem Analysis
Input : radius
Process : Calculate the area of a circle based on radius
Output : area

Algorithm (Pseudocode)
Begin
Read radius
if radius > 0
area = π x radius2
endif
Print area
End

Algorithm (Flowchart)

Begin

Read radius

T
radius > 0 area = π x radius2

F
Print area

End

Page 33
Pseudocode Scratch Code
if radius > 0

area = π x radius2

if radius > 0
area = π x radius2
endif

A Complete Scratch Program

Page 34
Tutorial 3 (Single Selection)
Write the problem analysis, pseudocode and flowchart for each question

1 If a student is in Modul 2 group, display the message “The student is taking Computer
Science subject”.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 35
2 Create a program that will accept student’s name and age. If the student’s age is below
45, the program will print a message “You are eligible to take a PhD program”.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 36
3 Display a message “You are an excellent student” for a student whose cumulative grade
point average (CGPA) is 3.75 or above.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 37
Enrichment Questions
4 Calculate the BMI of a person if height value entered is not zero.

5 Calculate the area of a circle if the radius entered is a positive value.

6 Determine whether a number entered by a user is an even number.

7 The contestant of ‘I Want to be A Millionaire’ must be at least 25 years old. Prepare a


pseudocode to print the message “You are qualified!” if the contestant is qualified.

8 Display a message “Congratulations! First Class Students” for a student whose cumulative
grade point average (CGPA) is 3.70 or above.

* Student can write the answer using example answer sheet at Appendix A

Page 38
CHAPTER 4
DUAL SELECTION CONTROL STRUCTURES
Learning Objectives
In this chapter, you will learn about:
a) Dual selection control structure and its’ respective purposes, and
b) Applying dual selection control structures in computational problem solving.

4.1 Introduction
Dual selection will check one (1) condition to choose between two (2) actions.
If condition is true, then perform action1, otherwise (if condition is false), then perform
action2

Pseudocode General Format Flowchart General Format

if (condition) T
condition
action1
else
F action1
action2
endif action2

Pseudocode Code Blocks

if (condition)
action1
else
action2
endif

Page 39
Problem Statement 1.1:
Print "Negative" for a negative number. Otherwise print "Positive".

Problem Analysis
Input : number
Determine message "Negative" or message "Positive" of a number
Process :
based on number
Output : message "Negative" or message "Positive"

Algorithm (Pseudocode)
Begin
Read number
if number < 0
Print "Negative"
else
Print "Positive"
endif
End

Algorithm (Flowchart)

Begin

Read number

T
number<0
Print "Negative"

Print "Positive"

End

Page 40
Pseudocode Scratch Code

Begin

Read num

if num < 0

Print "Negative"

Print "Positive"

End

A Complete Scratch Program

Page 41
Problem Statement 1.2:
Determine status of a student (Pass or Fail) based on mark. (Passing mark is 50)

Problem Analysis
Input : mark
Process : Determine status based on mark
Output : status

Algorithm (Pseudocode)
Begin
Read mark
if mark >= 50
status = "Pass"
else
status = "Fail"
endif
Print status
End

Page 42
Algorithm (Flowchart)

Begin

Read mark

T
mark >= 50 status = “Pass”

status = ‘Fail’

Print status

End

Page 43
Problem Statement 1.3:
Determine the status of a number, even or odd.

Problem Analysis
Input : number
Process : Determine status even or odd based on number
Output : Message "Even" or message "odd".

Algorithm (Pseudocode)
Begin
Read number
if number is divisible by 2
Print "Even"
else
Print "Odd"
endif
End

Page 44
Algorithm (Flowchart)

Begin

Read mark

T
num%2=0 Print “Even”

Print “Odd”

End

Page 45
Problem Statement 1.4:
An allowance for a part time lecturer will be paid monthly based on the total lecture
hours per month. Payment rate is as follows:

First 12 hours - RM 100 per hour


Additional hours - RM 50 per hour

Calculate the monthly allowance for a part time lecturer.

Problem Analysis
Input : hour
Process : Calculate allowance based on hour
Output : allowance

Algorithm (Pseudocode)
Begin
Read hour
if hour ≤ 12
allowance = hour x 100
else
allowance = 1200 + (hour – 12) x 50
endif
Print allowance
End

Page 46
Algorithm (Flowchart)
Begin

Read hour

T
hour ≤ 12 allowance = hour x 100

allowance = 1200 + (hour – 12) x 50

Print allowance

End

Page 47
Tutorial 4 (Dual Selection)
Write the problem analysis, pseudocode and flowchart for each question

1 If a student is in Modul 2 group, display the message “The student is taking Computer
Science subject”. Otherwise, display the message “The student is taking Biology
subject”.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 48
2 Determine whether a number entered by a user is divisible by 5 or not.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 49
3 MyHealth magazine is sold at RM5 each if at least 5 units of the magazine are
purchased, and it is sold at the price of RM7 each otherwise. Calculate the price a
customer has to pay after he enters the quantity of the magazines that he purchased.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 50
Enrichment Questions
4 A program will asks user to enter age for two peoples, where the values entered will be
stored in variables age1 and age2. Display “The first person is older” when age1 is
greater than age2, else display “The second person is older”.

5 Calculate BMI when a user enters weight and height. Print “Please reduce your weight”
if BMI is greater and equal to 25.0. If not, print “You have an ideal weight”.

6 A customer who rents a car will be charged RM60 if he rents for only 24 hours or
less. Otherwise, RM5 per hour will be charged for additional hours. Calculate and
display the charge of a car rental.

7 Calculate electric bill based on the electricity usage in watt as given below:

Usage up to 1000 watt - charge is 20 cents per watt.


Additional usage after 1000 watt - charge is 10 cents per watt.

8 Calculate how many litres of petrol (RON 95) that someone gets if 1 liter costs RM1.80.

9 There are two shapes that attached together; a square and a circle. Calculate:

(a) The total area.


(b) The total perimeter.

Page 51
10 ‘Fifie Boutique’ will organize a ‘Jumbo Sale’ next week. Each item will get a discount
based on the code colour shown below:

Code Colour Discount


Purple 30%
Yellow 50%
Calculate the sale price that customer should pay.

11 A program will accept two positive integers from user. The program will subtract the
bigger number with the smaller number.

12 Accept a diameter of a circle from user. If the diameter is an even value, find the
circumference of a circle. Otherwise, find the area of the circle.

13 User enters two numbers. Calculate and display the subtraction between those numbers
if the first number is bigger than the second number. Otherwise, calculate the product
of those numbers.

14 A program will accept two integers from user. Calculate the total of the two integers
if only both integers are negative. Then, find the product of those integers regardless
the value of those integers. Display the answers.

15 Refer to the table below:

Item Price
Sport Shoe RM69
Sandal RM24
The table shows the price of two items at ‘Marryeah’ store. During ‘Year End Sales’,
every purchase of RM40 will get one pair of socks as a free gift. Calculate the total pair
of socks that customer will get based on their purchase.
16 ‘WangiScented’ will open their 22th branch next month. Any purchase above RM100
will get 22% discount. Otherwise, no discount will be given.

Page 52
17 Calculate the total of electric bill. Users will provide their current meter reading and
previous meter reading. The rate of bill as follow:

Amount unit consumed Charge


First 100 units RM0.20 per unit
Next additional units RM0.23 per unit

18 Below is the rate of taxi charges:

During the day RM2 per km


During the night Charge is double
Find the charges based on the time (day/night) and the distance (km).

19 Hypermart ‘Supra Jimat’ provide a parking space for their customer’s convenience.
The first 3 hours is charge RM2 only. Next additional hour is charge RM1 per hour.
The parking fee during the weekend is double than during the weekday. Privilege of
free parking will be given to the customers with the total purchase above RM200.

20 A bookstore has made a promotion that offers a 20% discount for a book which RM
80.00 or more, and only 10% discount for book which price is less than RM 80.00.
Calculate the sale price of a book according to the promotion.

21 A program will accept two integers from user. Then the program will calculate the sum
and the difference of these two numbers. The output should be in the positive value
only.

22 ‘Hooray’ is one of an online shopping platform. Additional RM7.00 of shipping cost


will be added in the bill. During ’02.02.2020’ sales, it offers a free shipping with
minimum RM12 purchase. Calculate the total cost the customer should pay based on
their amount of purchase.

23 ‘FastPlus’ is a company that offers an e-hailing service. Passenger could make a request
using an online application. The fare is calculated based on the distance from the pickup
station to the desired destination. The basic fare is RM4 while the normal rate is
RM1.10 per km. The total fare is subject to which amount is higher.

* Student can write the answer using example answer sheet at Appendix A

Page 53
CHAPTER 5
MULTIPLE SELECTION CONTROL STRUCTURES
Learning Objectives
In this chapter, you will learn about:
a) Multiple selection control structure and its’ respective purposes, and
b) Applying multiple selection control structures in computational problem solving.

5.1 Introduction
Multiple selection control structure checks many conditions to choose between many actions
Condition will be checked one by one
When a condition is true, performs the action and stops checking the rest.

Pseudocode General Format


if (condition1)
action1
else if (condition2)
action2
else if (condition3)
action3
else
action4
endif

Page 54
Flowchart General Format

T
condition1 action1

T
condition2 action2

T
condition3 action3

action4

Pseudocode Code Blocks



if (condition1)
action1
else if
(condition2)
action2
else if
(condition3)
action3
else
action4
endif

Page 55
Problem Statement 1.1:
Determine the grade for a student from the given table below:
Grade Mark
A 80 – 100
B 70 – 79.99
C 50 – 69.99
D below 50

Problem Analysis
Input : mark
Process : Determine grade based on mark
Output : grade

Algorithm (Pseudocode)
Begin
Read mark
if mark >= 80
grade = ‘A’
else if mark >= 70
grade = ‘B’
else if mark >= 50
grade = ‘C’
else
grade = ‘F’
endif
Print grade
End

Page 56
Algorithm (Flowchart)

Begin

Read mark

T
mark >= 80 grade = ‘A’

T
mark >= 70 grade = ‘B’

T
mark >= 50 grade = ‘C’

grade = ‘F’

Print grade

End

Page 57
Scratch Code

Page 58
Problem Statement 1.2:
Determine the tax amount based on salary.
Tax (%) Salary (RM)
0 below 5,000
5 5,001 – 10,000
10 10,001 – 50,000
15 over 50,000

Problem Analysis
Input : salary
Process : Determine tax amount based on salary
Output : tax amount

Algorithm (Pseudocode)
Begin
Read salary
if salary < 5000
tax = 0
else if salary <= 10000
tax = 5% x salary
else if salary <= 50000
tax = 10% x salary
else
tax = 15% x salary
endif
Print tax
End

Page 59
Algorithm (Flowchart)

Begin

Read salary

salary < T
5000
tax = 0

salary < T
10000
tax = 5% x salary

salary < T
tax = 10% x salary
50000

tax = 15% x salary

Print tax

End

Page 60
Problem Statement 1.3:
Calculate water bill based on water consumption as given below:

Usage Charge
Usage of first 20 m3 charge is 40 cents per m3
Additional usage up to 20 m3 charge is 20 cents per m3
Extra usage charge is 10 cents per m3

Problem Analysis
Input : usage
Process : Calculate bill based on usage
Output : bill

Algorithm (Pseudocode)
Begin
Read usage
if usage <= 20
bill = 0.40 x usage
else if usage <= 40
bill = (0.40 x 20) + 0.20 x (usage – 20)
else
bill = (0.40 x 20) + (0.20 x 20) + 0.10 x (usage – 40)
endif
Print bill
End

Page 61
Algorithm (Flowchart)

Begin

Read usage

usage <= T
bill = 0.40 x usage
20

usage <= T
bill = 8 + 0.20 x (usage – 20)
40

bill = 12 + 0.10 x (usage – 40)

Print bill

End

Page 62
Tutorial 5 (Multiple Selection)
Write the problem analysis, pseudocode and flowchart for each question

1 Determine whether the number keyed in by user is positive, negative or zero.


a) Problem analysis

b) Pseudocode

c) Flowchart

Page 63
2 Create a program that will ask a user to enter age for two people. Display “The first
person is older” when age1 is greater than age2, else display “The second person is
older”. If both are not true, display “Both persons are same age”.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 64
3 This program prompts a user to key in a number as a choice for his/her favorite holiday
destination. If the choice is 1, it will display “Pulau Langkawi”. If the choice is equal
to 2, it will display “Cameron Highland”. If the choice is 3, it will display “Genting
Highland”, and it will display “Bukit Merah” if the choice is equal to 4. Otherwise, a
message “Your choice is not in the list” will be displayed.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 65
Enrichment Questions
4 The products listed below are sold in a convenience store:

Product Code Price (RM)


A 32.10
B 75.30
C 24.60

When a customer makes an order for a product, he/she is required to provide its
product code as well as the quantity.

Write an algorithm which accepts the code and quantity of one product to be
purchased and then output the amount to be paid for that purchase.

5 A student’s grade will be given based on the student’s mark for a subject. Determine
the student’s grade according to the following table:

Marks Grade
80 – 100 A
70 – 79 B
50 – 69 C
40 – 49 D
0 – 39 F

Page 66
6 A program will be assigned based on the value of a code. Display the name of the
program that will be assigned based on the following table.

Code Program

1 Degree in Computer Science


2 Degree in Information Technology
3 Degree in Computer Engineering
4 Degree in Electrical Engineering

7 Calculate phone bill based on the following term:

Usage Discount

Usage less than RM50 per month no discount will be given


Usage greater than RM50 but less than
get 5% discount
RM100 per month
Usage RM100 above per month get 20% discount

8 Determine the smaller number and larger number between two numbers entered by
user. Print the smaller number followed by the larger number if they are not equal.
Otherwise, print the message “The numbers are equal”.

Page 67
9 Prepare an IPO chart and a flowchart to calculate the total fees of parking based on
the table below:

Duration Charge
First half an hour Free
More than 30 minutes to one hour RM 1.00
More than one hour RM 0.20 every 10 minutes

The additional minutes after one hour is calculated only in multiple of 10. Otherwise,
it will be not included in the fees.

10 Calculate the amount paid for items bought at the supermarket based on the
following:

For purchase greater than and equal RM100 – discount will be given 5%.
For purchase greater than and equal RM150 – discount will be given 20%.
For purchase greater than and equal RM200 – discount will be given 30%.

11 Bantuan Sara Hidup (BSH) will be given to the family which has an income as
below:

Income BSH
Married
RM3000 and below RM950
RM3001-RM4000 RM750
Bachelor
RM2000 and below RM450
RM2001-RM3000 RM250

Determine and display the amount of BSH for a qualified user. Otherwise display
“Wrong input”.

Page 68
12 A software company offers training classes to people for learning how to use their
new product. Group registration receives discount as below:

Number of registrants in the group Fee per registrant


1-5 RM100
6 - 10 RM80
11 or more RM60

Ask for the number of registrants. If the input value is 0 or negative, display “Input
error” and don’t do anything else. If the number of registrants is a positive value,
calculate and display the total fee according to the rate listed in the table above.

13 The final match of Piala Pengarah KMKt will be held next week. The seating cost

are:Orange seats RM23.50, brown seats RM19.75, and yellow seats RM16.55.

There is a tax of 6% on all seats. Assume that one person can only buy one seat per
purchase.

14 ‘Seteroberi Resort’ located at Tanah Rata, Cameron Highlands. The resort provides
three types of room. The table shows information for each room.

Charge rate (RM) per


Room Type Deposit (RM)
night
Studio room (S) 390
Family suite (F) 200 * no. of rental days 500
Penthouse (P) 600

Based on the information given, calculate the deposit, total payment and balance
payment after deposit paid. The user need to enter the room type based on customer
choice. Display “Wrong Room Type” if the user enters wrong room type. Repeat the
process until ‘Z’ is entered.

15 A program will accept two integer values from user. If any of the numbers entered is
negative, the message “Numbers entered must be non-negative” will be displayed and
the program terminates. Otherwise, it will display the sum of two numbers only if the
first value is less than a second value. Otherwise, the product of the two numbers will
be displayed.

Page 69
16 Ceria Bookstore Sdn. Bhd. is a company that sells various of books and stationaries.
Members of this book store will get special discounts based on accumulate points.
Every purchased of RM3.00 will get one point. Discount will be given base on the
following table.

Accumulate Points Discounts

300 30%
500 35%
600 40%

Calculate the total price customer should pay if the discount is valid only in a single
receipt.

17 Create a program to find the median number among three numbers.

Sample Output :

Input the first number: 25


Input the Second number: 37
Input the third number: 29
Expected Output:

The median value is 29.0


18 Input an integer number, num. Determine whether numis either :

a. Divisible by both numbers 2 and 7; or


b. Divisible by 2 only; or
c. Divisible by 7 only; or
d. NOT divisible by 2 and 7.

Display an appropriate message.

* Student can write the answer using example answer sheet at Appendix A

Page 70
CHAPTER 6
REPETITION CONTROL STRUCTURES
COUNTER-CONTROLLED
Learning Objectives
In this chapter, you will learn about:
a) Counter-controlled repetition control structure and its’ respective purposes, and
b) Applying counter-controlled repetition control structures in computational problem
solving.

6.1 Introduction
Counter-controlled repetition is used when we know the number of iterations we have to
perform i.e. we know how many times we need to execute a loop.
Counter-controlled repetition involves three (3) basic processes:
• Initialization (Set the initial value of the loop control variable).
• Evaluation (Test the loop control variable to determine whether the loop should
continue or stop).
• Updating (Increment/decrement the value of the loop control variable).

*The loop control variable is the variable that control the number of times the loop is
executed.

General Format for Pseudocode (Counter-controlled)


Start
counter initialization //initialization
while condition //evaluation
statement block
counter increment/decrement //updating
endwhile
next action
End

Page 71
Flowchart General Format (Counter-controlled)

Start

counter initialization

F
condition

statement block next action

counter increment/decrement

Stop

Pseudocode Code Blocks

counter initialization

while condition

counter increment/decrement

Page 72
Problem Statement 1.1:
Print message "Hello, world!" 10 times.

Problem Analysis
Input : No input
Process : Repeat print the output 10 times.
Output : 10 messages "Hello, world!"

Algorithm (Pseudocode)
Begin
set counter to 0
while counter < 10
Print "Hello, world!"
counter = counter + 1
endWhile
End

Desk-checking

counter counter < 10 Print


0 T √
1 T √
2 T √
3 T √
4 T √
5 T √
6 T √
7 T √
8 T √
9 T √
10 F

Here,

• last value for counter is 10


• no. of looping = no. of true = 10
• the loop will stop once the condition is false.

Page 73
Algorithm (Flowchart)

Begin

counter=0

F
counter<10 End

Print “Hello, world!”

counter = counter + 1

Scratch Code

Page 74
Problem Statement 1.2:
Calculate and print sum of 10 numbers entered by user.

Problem Analysis
Input : 10 numbers
Process : Repeat adding number to sum 10 times.
Output : sum

Algorithm (Pseudocode)
Begin

sum=0
counter = 0
while counter < 10
Read num
sum = sum + num
counter = counter + 1
endwhile
Print sum
End

Desk-checking

sum counter num counter < 10


0 0 2 T
2 1 10 T
12 2 8 T
20 3 4 T
24 4 3 T
27 5 7 T
34 6 5 T
39 7 4 T
43 8 7 T
50 9 2 T
52 10 F

Page 75
Algorithm (Flowchart)

Begin

sum=0
counter=0

F
counter<10 print sum

T
End

Read num

sum = sum + num


counter = counter + 1

Page 76
Problem Statement 1.3:
Calculate and print sum and average of 10 numbers entered by user.

Problem Analysis
Input : 10 numbers
Repeat adding number to sum 10 times.
Process :
Calculate average
Output : sum, average

Algorithm (Pseudocode)
Begin

sum=0, average=0
counter = 0
while counter < 10
Read num
sum = sum + num
counter = counter + 1
endwhile
average = sum / counter
Print sum, average
End

Desk-checking

sum average counter num counter < 10


0 0 0 2 T
2 1 10 T
12 2 8 T
20 3 4 T
24 4 3 T
27 5 7 T
34 6 5 T
39 7 4 T
43 8 7 T
50 9 2 T
52 10 F
5.2

Page 77
Algorithm (Flowchart)

Begin

sum=0
average=0
counter=0

F
counter<10 average = sum / counter

T
print sum, average
Read num

End
sum = sum + num
counter = counter + 1

Page 78
Problem Statement 1.4:
Determine the number of marks which are above 80 among 100 marks entered by
user.

Problem Analysis
Input : 100 marks
Repeat checking each mark entered whether greater than 80, and
Process :
increment counter by 1 if true.
Output : the number of marks above 80

Algorithm (Pseudocode)
Begin
bil = 0
counter = 0
while counter < 100
input mark
if mark > 80
bil = bil + 1
endif
counter = counter + 1
endwhile
Print bil
End

Page 79
Algorithm (Flowchart)
Problem Statement 1.5:
Calculate and print the minimum value among 10 numbers entered by user.
Begin

bil = 0
i=0

F
counter < 10 Print bil

T
End
Input mark

F
mark > 80

bil = bil + 1

counter = counter + 1

Page 80
Problem Analysis
Input : 10 numbers
Read first number and set as minimum value
Process : Repeat compare each number entered to the minimum value, and
keep the minimum value.
Output : minimum value

Algorithm (Pseudocode)
Begin
Read num
min = num
counter = 1
while counter < 10
Read num
if num < min
min = num
endif
counter = counter + 1
endwhile
Print min
End

Desk-checking

num num < min min counter counter < 10


7 7 1 T
8 F 2 T
9 F 3 T
4 T 4 4 T
3 T 3 5 T
6 F 6 T
9 F 7 T
2 T 2 8 T
5 F 9 T
3 F 10 F

Page 81
Algorithm (Flowchart)
Problem Statement 1.5:
Calculate and print the minimum value among 10 numbers entered by user.

Begin

Read num

min = num
counter = 1

F
counter<10 print min

T
End

Read num

T
num<min min = num

counter = counter + 1

Page 82
Problem Statement 1.6:
Calculate and print the largest value from a list of five numbers.

Problem Analysis
Input : 5 numbers
Read first number and set as largest value
Process : Repeat compare each number entered to the largest value, and keep
the largest value.
Output : largest

Algorithm (Pseudocode)
Begin
Read num
max = num
counter = 1
while counter < 5
Read num
if num > max
max = num
endif
counter = counter + 1
endwhile
Print max
End

Desk-checking

num num > max max counter counter < 5


7 7 1 T
8 T 8 2 T
9 T 9 3 T
4 F 4 T
3 F 5 F

Page 83
Algorithm (Flowchart)

Begin

Read num

max = num
counter = 1

F
counter<5 print max

T
End

Read num

T
num>max max = num

counter = counter + 1

Page 84
Tutorial 6 (Counter-controlled Repetition)
Write the problem analysis, pseudocode and flowchart for each question

1 Calculate the sum and average of 20 marks entered by user.


a) Problem analysis

b) Pseudocode

c) Flowchart

Page 85
2 Print the squares of 10 numbers entered by user.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 86
3 Calculate the BMI for 15 students.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 87
Enrichment Questions

4 Calculate the average of three tests for 30 students.

5 Calculate the sum of 1000 numbers that are being input interactively using a loop.

6 Display odd numbers from 3 to 39.

7 Print multiples of 5 which are less than 30.

8 Calculate the total for the first 20 positive integers.

9 Calculate the average for the first 10 positive even numbers.

10 Given a list of daily temperature for a certain number of days. Calculate the total
temperature. The first input is the number of days.

11 A program will determine the total and average price for a few items bought by a
user. The number of items will be entered by user at the start of the program.

12 Print odd numbers between 1 and 40.

13 A program is used to find the average of a number of tests taken by a student. The
number of test is varies between subjects. The program will allow the lecturer to key
in the number of test before he can key in the test marks for a student.

14 User will enter ten numbers into a program. The program will:

(a) Determine the maximum and the minimum number.


(b) Then, find the difference between the maximum and the minimum.

15 User will enter 100 numbers randomly. Count the even numbers amongst those
numbers.

16 A program will determine the highest mark amongst 30 students. Then the name of
the student will be display as the output.

17 A program will accept 50 numbers from user and determine whether there are more
even numbers than odd numbers or vice versa.

* Student can write the answer using example answer sheet at Appendix A

Page 88
CHAPTER 7
REPETITION CONTROL STRUCTURES
SENTINEL-CONTROLLED
Learning Objectives
In this chapter, you will learn about:
a) Sentinel-controlled repetition control structure and its’ respective purposes, and
b) Applying sentinel-controlled repetition control structures in computational problem
solving.

7.1 Introduction
Sentinel-controlled is used when you are not sure about the iterations but you know what the
condition is and then you can loop that block until the condition is false.

In sentinel-controlled repetition the number of loop is NOT known before the loop begins
executing. The loop will stop when a sentinel value is reached. Sentinel value is a special value
such as 0, -1, 999, ‘Y’, ‘N’, true, false to indicate the end of data entry.

General Format for Pseudocode (Sentinel-controlled)


Start
First input //initialization
while condition //evaluation
statement block
next input //updating
endwhile
next action
Stop

Page 89
Flowchart General Format (Sentinel-controlled)

Start

initialization

F
evaluation

statement block next action

updating

Stop

Pseudocode Code Blocks

First input

while condition

Next input

Page 90
Problem Statement 1.1:
Calculate and print sum and number of positive numbers entered by user until user
keyed in 0.

Problem Analysis
Input : A few numbers
Repeat checking each number entered and adding it to sum while the
Process :
number is not 0.
Output : sum, number of positive numbers (count)

Algorithm (Pseudocode)
Begin

sum=0, count=0
Read num
while num > 0
sum = sum + num
Read num
count = count + 1
endwhile
Print sum, count
End

Desk-checking

sum count num num>0


0 0 2 T
2 1 5 T
7 2 3 T
10 3 0 F

Page 91
Algorithm (Flowchart)

Begin

sum=0
count=0

Read num

F
num >= 0 print sum, count

T
End
count = count + 1
sum = sum + num

Read num

Page 92
Problem Statement 1.2:
Calculate and print sum and average of numbers entered by user until user keyed in
negative value.

Problem Analysis
Input : A few numbers
Repeat adding number to sum until user enter negative value.
Process :
Calculate average
Output : sum, average

Algorithm (Pseudocode)
Begin

sum=0, average=0, count=0


Read num
while num >= 0
count = count + 1
sum = sum + num
Read num
endwhile
average = sum / count
Print sum, average
End

Desk-checking

sum average count num num>=0


0 0 0 4 T
4 1 4 T
8 2 4 T
12 3 0 T
12 4 -1 F
3

Page 93
Algorithm (Flowchart)

Begin

sum=0
average=0
count=0

Read num

F
num >= 0 average = sum / count

T
print sum, average
count = count + 1
sum = sum + num

End

Read num

Page 94
Scratch Code

Page 95
Problem Statement 1.3:
Create a program that keeps asking the user for a number and printing the square
root of the number entered. The program ends when the user enters a negative
number.

Problem Analysis
Input : A few numbers
Process : Repeat reading a number and calculate the square root of the
number, until the number entered is a negative number.
Output : square root of each number

Algorithm (Pseudocode)
Begin

Read x
while x > 0
sqroot = x1/2
Display sqroot
Read x
endwhile
End

Desk-checking

x x>0 sqroot
9 T 3
25 T 5
36 T 6
4 T 2
49 T 7
0 F

Page 96
Algorithm (Flowchart)

Begin

Read x

F
x>0 End

sqroot = x1/2

Print sqroot

Read x

Page 97
Tutorial 7 (Sentinel-controlled Repetition)
Write the problem analysis, pseudocode and flowchart for each question

1 Design an algorithm for a program that will accepts a list of product price from user
and calculate the total price. The process will continue until the user enters value -1.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 98
2 Design an algorithm to calculate the total temperature for a list of daily temperatures
that will be entered by user. The calculation will stop when the value of temperature
entered is -999.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 99
3 A program will calculate the average for a few integers entered by user. The user should
key in 0 to terminate the sequence.
a) Problem analysis

b) Pseudocode

c) Flowchart

Page 100
Enrichment Questions
4 Calculate the average of a few students’ height. The negative value for height indicates
the end of input.

5 A program will accept a series of numbers from user and determine whether each
number entered is an even or odd number. The program will stop when a user enters
0.

6 Create an algorithm that will accept input age, height and weight for some student.
The loop will stop when the user enters value 0 for age. Calculate the average for age,
height and weight. Print the number of people and the average age, height and weight.

Page 101
APPENDIX A – ANSWER SHEET
Question: (write the question here)

Problem analysis Pseudocode Flowchart

You might also like