Beruflich Dokumente
Kultur Dokumente
Programming
LEARNING OUTCOMES
At the end of this topic, you should be able to:
1. Define the meaning of programming and computer program with
accuracy; and
2. List six process steps that are involved in developing a program.
X INTRODUCTION
Since its introduction, computers have helped a lot in making everyday human
tasks easier. With the help of a computer, we can pay bills, do banking, even
shop without moving from our seat. You would have used the Automatic Teller
Machine (ATM). Imagine what would happen if computers are not used?
This chapter will discuss programming concepts and the processes that are
involved in developing a program.
ACTIVITY 1.1
Before you start reading, what can you say about a program?
Whereas
Each of these phases is divided into several parts. Refer to Figure 1.1 which
shows the relationship between these two phases.
We will discuss in detail how these three steps are carried out.
(a) Analysis
Analysis is the process of understanding and defining a problem. At this
stage, a programmer should try to state the problem clearly and understand
what needs to be done to solve the problem. We may need to know more
detailed information from the persons who have identified the problem.
During analysis, ensure you understand and define the problem correctly.
Once the sub-problem is identified, we can solve each sub-problem one at a time.
(c) Walkthrough
Walkthrough is one of the steps in algorithm design that is almost always
forgotten.
(b) Testing
Testing a program code is a process of running a program and checking for
errors. This is to ensure the program does what it is intended to do.
Normally, testing is carried out by running the program code repeatedly
using a set of different data to ensure it functions properly for every
situation. Large input size that cannot be tested by hand has to be tested
now. If an error is found, the program needs to be modified until it
produces the right output or answer.
(c) Maintenance
Maintaining and updating a program code involves tasks in modifying the
program code to eliminate errors that could not be found before and update
it according to current changes in the organisationÊs rules and policies.
Usually, maintenance work is carried out every five years and the
programmer that developed the program would have left the organisation.
Therefore, it is important for a programmer to write programs that are easy
to read, understand and maintain. Thus, we must adhere to programming
styles that are accepted by the programming society.
You have now been briefed on all the processes involved in the problem
solving phase and the implementation phase. If you are still not clear,
please read through the text again.
To ensure you have understood what you have learnt, answer the following
questions.
TOPIC 1 INTRODUCTION TO PROGRAMMING W 6
SELF-CHECK 1.1
1. What is meant by a program?
2. At which phase is the algorithm created?
3. At which phase is the written algorithm translated into a
computer program?
4. The programming process is divided into two. State the
processes that are involved in each.
LE ARNING OU TCOME S
At the end of this topic, you should be able to:
1. Solve problems by using two algorithm representative techniques;
2. Test the algorithm execution process with step-by-step detailing; and
3. Build a complex algorithm by using selective or repetitive control
structure.
X INTRODUCTION
In Topic 1 you were introduced to two main phases in developing a program.
One was the problem-solving phase. In this phase, you were given some
explanation on algorithms. Therefore in this topic, you are required to focus
entirely on algorithms from the aspect of representation until implementation.
From a historical point of view, Alkhwarizmi (Algorithm) was a mathematician.
This means that the steps will have an end and will stop. At every step, the
following action taken should uniquely be determined by instructions and
data obtained at that time.
2.1 ALGORITHMS REPRESENTATION
In order to represent algorithms by using flow charts, we can use the following
as a guide:
1. Identify the symbol used according to its function.
2. Get the right formula.
3. Make sure that appropriate data is used.
4. Test the flow chart by tracing each symbol and comparing it with the
expected output.
TOPIC 2 ALGORITHM W 9
Based on the guide given above, let us see an example as in Figure 2.2 of a flow
chart on starting a car engine.
ACTIVITY 2.1
Sketch a flow chart for the process of going for a tutorial session.
Pseudo-code or false codes are instructions that mimic the program code
(actual program instructions).
TOPIC 2 ALGORITHM W 10
Where the flow charts uses diagrams, pseudo-codes are written using phrases or
words. To represent algorithms using pseudo-codes, we need to follow the rules
of writing pseudo-codes as follows:
1. Every step in an algorithm should not have more than two actions.
2. Steps in an algorithm are executed in sequence.
3. The word end or stop is used to show that the process has been ended.
4. The selection structure is also stated in shapes which will also be explained
later. (Refer to Part 2.4)
5. Loops are stated in one of the shapes which will be explained later. (Refer to
Part 2.5)
6. The action that is allowed includes declaring variable names to identify the
set of variables that have a corresponding data type. Types of data might be
integer, real, character or others.
7. To give an initial value to a variable (if applicable).
8. To use arithmetic symbols to state the addition, subtraction, multiplication,
division operations and brackets to show operation priority.
9. A ® B represents exchanging the value of A with B.
10. The relational operators below are used to state the relationship between
two values:
(a) < Less than
(b) <= Less than or equals to
(c) > More than
(d) >= More than or equals to
(e) ! = Not equal
(f) == Equal
Example 2.1
Change mm unit to kg.
If you want to test your understanding of this topic, try to answer the
questions below.
SELF-CHECK 2.1
ACTIVITY 2.1
Input is all the information that is relevant, needed to execute a process. Usually
the information of the input is inserted in the problem statement given.
Output is the result that is needed. The format on how the output is to be displayed
has also to be identified during the construction of the algorithm. An example of
the output format for display is usually in the form of a table. Below is the input
and output that has been identified for some examples of problems.
Example 2.2
Example 2.3
Example 2.4
Given the buying and selling price of an item, determine whether profit
was made, or broke even or loss incurred
Input: i. Buying price (in ringgit)
ii. Selling price (in ringgit)
Output: Message "Profit" or "Break Even" or "Loss"
When the input and output are known, we need to build a list of formula that
will relate to each other. Based on Example 2.4, the general formula obtained is:
To ensure that you have understood what has been learnt, try to answer the
following question. Good Luck!
SELF-CHECK 2.2
Before continuing to the next topic, it would be good to rest for a while, because
the next topic needs your full attention.
TOPIC 2 ALGORITHM W 14
Example 2.5
Given the name of a student, calculate the number of the letter ÂaÊ in the
name.
Solution
The name of a student can be made up of more than one word. To count
the number of ÂaÊs in it, we need to get each letter and compare them. We
need to have a variable to act as a counter to track the number of ÂaÊs that
exist. The letter ÂaÊ can exist in uppercase or lowercase letter. For example,
in the name "Tatenda Amani" there are 4 'a' s.
Step 2 and 4 can be done easily. But step 3 needs refinement. Step 3 looks like a
sub-problem that seems easy but if it is to be solved using a computer; we need
to have detailed steps on how it is to be executed by a computer. Notice how the
refinement is done by using the guide given next.
Next is the complete explanation on algorithm that is re-written for Example 2.5.
1. Start.
2. Input studentÊs name: studName.
3. Count the number of Âa's in studName.
3.1 Set n = 1 and totalA = 0
3.2 Until more characters to be read, execute the
following step. If not, continue to step 4.
3.2.1 Read n-character
3.2.2 If n-character is the same as 'A' or 'a', add 1 to totalA.
3.2.3 Increase n by 1.
4 Report "Number of ÂaÊs is totalA".
5. End.
In this easy example, the number of levels refined is only up to 2 levels. One of
the main steps which is step 3 is refined to be step 3.1 and 3.2. Then 3.2 is refined
further into steps 3.2.1, 3.2.2 and 3.2.3. For more complex problems, the level of
TOPIC 2 ALGORITHM W 16
refinement may be more until each step becomes detailed and can be executed.
Below are a few guides to summarise the solution:
Selection structure is a structure design that gives a few choices during execution.
The choices made are dependent on the conditions that are given. There are 3 types
of general selection structures, which are:
1. Single Selection
2. Dual-selection
3. Multi-selection
step a
If <Condition true>
Start_If
step 1
step 2
:
step k
End_If
Step k+1
If the condition is met, step 1 till step k will be executed. Then, step k + 1 is
executed. Alternatively, if the condition is not met, step k + 1 will be executed
without executing step 1 to step k.
Step 1 to step k is also known as the start_if and end_if block. Here we will see
that step k+1 will always be executed whether the condition is met or not met.
Step a which is put before the start_if and end_if block will always be executed
because the testing of the condition is after step a.
Note: Notice the indentation for steps in the block start_if ă end_if that are
indented a little bit. This is to show that the steps are dependent on the results
that are obtained from the testing of the condition that is done.
Example 2.6
Determine if the customers deserve to get a discount of US10.00
from the total payment charged. Customers will be categorised
as deserving if the total_payment is US60.00.
1.0 Start.
2.0 Input total_payment value
3.0 If (total_payment > 60)
4.0 Start_If
4.1 Minus 10 from the total_payment
5.0 End_If
6.0 Report actual total_payment
7.0 End
Note: Words that are written in italics like total_payment are variable names that
are recommended. Variables are words that can receive any type of value. You
are also free to use any other name as a variable. But it is good if the variable
name can reflect the task. As given above, total_payment is referring to the total
payment that is charged to the customer.
LetÊs now trace the algorithm. LetÊs say the total_payment is 80.00. Testing
done in step 3.0 is true because 80 > 60. Therefore, the control of the program will
enter the start_if-end_if block. This means, the total_payment will minus 10.
Then, the control of the program will exit from the block and execute step 6.0.
Therefore, the value of total_payment reported is 70.00.
ACTIVITY 2.3
How if the
reference.
TOPIC 2 ALGORITHM W 19
Figure 2.6: Flow chart for Example 2.5, single selection structure
Example 2.7
Determine the requirement of a student to sit for the examination
based on the number of lab sessions attended. The percentage of
attendance at the lab must be 80%. If it is less than that value, the
student is categorised as not qualified.
ACTIVITY 2.4
SELF-CHECK 2.3
2.3.2 Dual-selection
The dual-selection structure involves testing for two conditions. Choices that are
given are the same as single-selection that is whether the condition is met or not
met. The difference is, if the condition is not met, there are some steps to be
executed. To understand it further, letÊs look at the general algorithm below:
TOPIC 2 ALGORITHM W 21
If <true condition>
Start
step 1
step 2
:
step k
End_If
If_Not
Start
step k+1
step k+2
:
step n
End_If_Not
step n+1
If < true condition > steps in the start_if - end_if block will be executed. Then,
step n+1 will be executed ignoring the steps in the start_if_not - end_if_not block.
But if the condition is not true or not met, the start_if_not - end_if_not would be
executed without executing the steps in the start_if - end_if. Step n+1 will still
be executed whether the condition is met or not. This case is the same as in the
single selection.
A general form of a flow chart for the dual-selection is shown in Figure 2.7 below.
Example 2.8
Determine the payment that will be charged to a customer for
parking their car in a car park. The payment rate charges are, if
total time parked is 2 hours or
if the total time parked is more than 2 hours, then 6.00 is
charged.
Assume:
in_time = 9.00
out_time = 13.00
total_time = 13.00-9.00 = 4
Testing at step 5.0 will be false because 4 is larger than 2. This will cause the control
of the program to execute the start_if_not - end_if_not block. At the last step,
total_payment will be reported as 6. See Figure 2.8 for the example above.
TOPIC 2 ALGORITHM W 23
ACTIVITY 2.5
Now, can you try to solve the problem by using in_time 8.00 and out_time
17.00? Use Example 2.8 as a reference.
Example 2.9
Determine the payment that is charged to the customer
who parked their cars in the parking lot. The payment
rates charges are; 2.00 the first hour, and 1.00 for
each subsequent hour.
In the algorithm above, if total_time > 1, and letÊs say the total_time is 2, then,
start_if-end_if block (step 6.0-7.0) will not be executed. But the start_if_not-
end_if_not block (step 9.0-10.0) will be executed.
In step 9.3, total_time now becomes 3; because 1 plus 2 is 3. Here the value 2 is
for the payment rate for the first hour. You need to remember that the payment
for the first hour is different from the subsequent hours. Total payment reported
in step 11.0 is 3.
TOPIC 2 ALGORITHM W 25
ACTIVITY 2.6
Now try with the previous data which is the in_time 9:30 and out_time 4.30.
Use the algorithm given in Example 2.9 as a reference.
SELF-CHECK 2.4
2.3.3 Multi-selection
This is the last selection structure. In multi-selection we are allowed to choose
only one statement block from a number of blocks that exist. The number of
statement blocks depends on the number of conditions. If there are n conditions,
then there are n+1 statement blocks, because we have a last statement block that
is not tied to any of the conditions. In the general form below, the statement
blocks are from step q till r.
If <true condition1>
Start
step 1
step 2
⁄
step k
End_If1
If_Not
If<true condition2>
Start
step k+1
step k+2
⁄
step m
End_If2
⁄
⁄
If_Not
If<true condition h>
TOPIC 2 ALGORITHM W 26
Start
step n+1
step n+2
⁄
step p
End_If h
If_Not
step q
step q+1
⁄
step r
End_If_Not
Figure 2.9 shows the flow chart for the general structure of multi-selection.
Example 2.10
Input an integer number and determine whether that number
is negative, positive or zero. Print the results.
1.0 Start.
2.0 Read integer N
3.0 If (N < 0)
4.0 Start.
4.1 Print „N is negative‰
5.0 End_If1
6.0 If_Not
7.0 If (N > 0)
8.0 Start.
8.1 Print „N is positive‰
9.0 End_If2
10.0 If_Not
11.0 Start.
11.1 Print „N is zero‰
12.0 End_If_Not
13.0 End
LetÊs trace the example above. LetÊs say the value of N is 7. Testing at step 3.0 will
be false because 7 is larger than 0. Step 4.0 till step 5.0 is ignored. Testing at step
7.0, when executed, the result is true. Therefore, it will print „N is positive‰.
ACTIVITY 2.7
Try to trace for the value of 10 based on the algorithm above. What is the
printed result?
TOPIC 2 ALGORITHM W 28
Example 2.11
Input bus passenger age to determine the price of the tickets. If
the age of the passenger is 55 and above or between 6 to 12
years, then the ticket price is 50% of the normal ticket price. If
the passengerÊs age is between 12 to 18 years, then the ticket
price is only 75% of the normal ticket price. It is free for
passengers less than 6 years.
From the question given, we can conclude that there are 5 groups of passengers:
Figure 2.10 is a flow chart that shows a multi-selection structure. Trace Figure
2.10 and compare it with the conditions stated in Example 2.11. The flow chart is
as follows:
TOPIC 2 ALGORITHM W 29
For a loop controlling counter, the three components are put in special places,
such as:
start_for
step 1
step 2
:
} Loop Body
step n
End_for
If the counter value is still less than the last value, the step in the start_for- end_for
block, which is step 1 till n will be executed. This block is also known as the loop
body.
After the last step in the loop is executed, the value of the counter is updated
according to the increment that is stated. Notice however that the increment is
not necessarily by adding the counter by 1. The increment can be 2 or 3 times and
so on. After the counter has been updated, the test is done again and the
execution of the loop body repeats until the condition that is set on the counter is
no longer fulfilled.
The loop ends and the control will get out of the loop. The step after the end_for
will be executed. Figure 2.12 shows the general flow chart for the counter
controlled loop.
Example 2.12
In example 2.12, the start_for - end_for block will be executed 5 times. Therefore,
we need to trace the algorithm above and see the table given below.
i i < 10 Total
0
1 True 1 I (0+1)
3 I (1+2) True 4 I (1+3)
5 I (3+2) True 9 I (4+5)
7 I (5+2) True 16 I (9+7)
9 I (7+2) True 25 I (16+9)
11 I (9+2) False 25
The loop will stop when the counter I is more than 10, which is when iÊs value is
11. At that time the value of total is 25.
You need to remember that the initial_value must be a large value. After
the last step is executed, the value of the counter will be decreased
according to the rate specified. Just as in the increasing counter control
loop, the rate is not necessarily 1. Look at the example 2.13:
Example 2.13
Notice that in step 3.0, the initial_value is a large number that will be decreased
by 2 to decrease its initial_value. Next is the tracing of the loop:
i> = 1 Total
0
9 True 9 I (0+9)
7 I (9-2) True 16 I (9+7)
5 I (7-2) True 21 I (16+5)
3 I (5-2) True 24 I (21+3)
1 I (3-2) True 25 I (24+1)
-1 I (1-2) False 25
The loop will stop when the condition is not fulfilled, that is when the value of i
is -1. At that instant, the total is 25. The end result of total in the example with the
increasing counter and the total in the example with the decreasing counter is the
same.
TOPIC 2 ALGORITHM W 34
ACTIVITY 2.8
What is the effect if i minus 2 is replaced by i plus 2 in the Example
2.13 algorithm in step 3.0? Why does that happen?
Figure 2.13: General Form and Flow Chart of loop structure with condition tested first
TOPIC 2 ALGORITHM W 35
Example 2.14
Example 2.15
Consider the example for loops of this type:
1.0 Start.
2.0 Set total and counter to 0.
3.0 Start.
3.1 counter I counter + 1.
3.2 total I total + i.
4.0 End.
5.0 Until (counter less than 5).
6.0 Report total value
7.0 End.
End result of total is the same as the loop before this which is 15. Notice in
the tracing below, the number of tests for the condition in the condition
controlled loop for this form is one less than the condition in the condition
controlled loop in the form before this.
TOPIC 2 ALGORITHM W 37
Example 2.15
Read 1 set of studentsÊ marks where if the marks
are negative then the input ends. Calculate the
average marks.
In example 2.15, a negative mark input will end the loop because the test condition
(step 4.0) becomes false. In the example above, the number 999 can be a sentry value
because the maximum mark is 100. To make the number 999 as a sentry value, the
step 4.0 in the algorithm has to be changed to Until m!=999 that is when the mark
mi is 999, the statement becomes false and automatically comes out of the loop.
ACTIVITY 2.9
For the algorithm Example 2.15 above, what if the negative value is a valid
data?
Sentry value can also be of type character. We can change the example above and
use the character ÂtÊ as a sentry value. Consider the changes made in algorithm B
below.
Till now you have learnt three types of control structures. Rest and relax before
going on to the next topic.
TOPIC 2 ALGORITHM W 39
2.4.4 Structuring
This method is used to solve problems by designing structure charts. Benefits of
using the structure chart can be listed as:
(i) Able to identify the number of modules or sub-problems that are
created by breaking up the problem
(ii) Able to give input that is needed by a module or sub-problem that
can be shown in the chart
(iii) Able to determine the output that is obtained from one module
that can be used in other modules
(a) Problem
Solve the problem of calculating gross pay and net pay for workers that is
made up of basic pay and overtime pay. The normal working hours are 40
hours. The rate for working overtime is 2 times the normal rate. If the
workerÊs pay exceeds 500 per week, a tax of 50 is deducted.
(b) Analysis
To calculate the pay, the information needed are the hours worked and the
hourly rate. The net pay of a worker can be obtained by deducting tax from
the pay if the pay excee
Input:
Hours_Worked (float type)
Hourly_Rate (float type)
Output:
Gross_Pay (float type)
Net_Pay (float type)
TOPIC 2 ALGORITHM W 40
Relevant Formula:
Normal_Pay = Work_Hours x Hourly_Rate
Overtime_Pay = Overtime_Hours x Overtime_Rate x Hourly_Rate
Gross_Pay = Normal_Pay + Overtime_Pay
Net_Pay = Gross_Pay - Tax
(d) Design
Initial Algorithm:
1.0 Start
2.0 Read Hours_Worked and Hourly_Rate .
3.0 Calculate Gross_Pay.
4.0 Calculate Net_Pay .
5.0 Print Gross_Pay and Net_Pay.
6.0 End
Step 3.0 and step 4.0 can be refined. Normally, our operation uses
refinement to get the calculated gross pay and net pay.
SELF-CHECK 2.5
As an example:
Input: 3 7
Output: 3 4 5 6 7
Input: 7 3
Output: 7 6 5 4 3
îAlgorithm
îDual-Selection îFlow Chart îLoop
îMulti-selection