Computing Section 4 TV
Computing Section 4 TV
SECTION
4 COMPUTATIONAL
THINKING AND
PROGRAMMING
LOGIC
1
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
INTRODUCTION
Hello Learner, welcome to an exciting journey into the world of computational thinking
and programming! This section is designed to introduce you to the fundamentals of
creating algorithms and writing code, primarily using Python. As you embark on this
adventure, you will learn how to tackle problems by breaking them down, just like
computer programmers do when they develop software.
We will start by mastering basic programming concepts, such as variables, data types,
and arrays. These are the foundations you will use to build more complex programs as
you progress. Your teacher will guide you in using tools like pseudocode and flowcharts
to visually represent your solutions, making complex ideas simpler to understand and
implement.
Remember, learning to code is like learning a new language; it is about practice and
persistence. So, stay curious, ask questions and take advantage of this opportunity to
learn skills that are crucial in today’s digital world.
Key Ideas
1. Variables are named storage locations that hold a value or an object which can be
changed.
2. Computer programming is the process of writing code that tells a computer,
application, or software program what to do.
3. Algorithms are the steps by way of solving a problem.
4. Flowcharts are the use of shapes to represent the steps of solving a problem.
2
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Variable Naming
1. Choosing appropriate names for variables is important because it makes your
program easier to understand.
2. Always use variable names that clearly describe what they hold.
3
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
For example, use ‘Form1_Class_Register’ instead of ‘x’ because it tells you what
the variable represents.
It is important to note that each programming language has its own set of rules and
conventions for naming variables. It is important to learn these rules for the language
you are using.
Most programming languages, including Python, will not permit variable names to
start with a number and a variable name with more than one word cannot have a space
(use an underscore or camelCase).
This means that 1name or first name would not be permissible but name1 and first_
name or firstName would be acceptable. camelCase is a way to separate the words in
a phrase by making the first letter of the second and subsequent words capitalised and
not using spaces.
Activity 4.1
1. Identify and share with a friend 2 daily routines that could be described as a
step-by-step process of solving a problem(algorithm).
E.g.: Frying an egg
2. Identify which of the following algorithms for frying an egg is correct
Note that the process of frying an egg put together becomes an algorithm.
4
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Algorithms
An algorithm is a series of steps that you follow to solve a problem or complete a task.
Think of it like a recipe (instructions) in cooking that tells you what to do, step by step.
5
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
h. Arrive at school
i. Enter school premises
Note that an algorithm can be contained in another algorithm, for example
brushing teeth is an algorithm within the algorithm of a child getting ready for
school.
Also, for some children, the steps might be in a different order, like Step c (Wash)
being switched with Step b (Brush teeth), or the formula might be more detailed,
for example replacing Step a (Wake up) with additional steps such as Turn off
alarm clock, Get out of bed and Make bed.
2. Another example of an algorithm could be for a child eating breakfast. This
example involves an iteration (repetition)
a. Put porridge in a bowl
b. Add sugar and milk to the porridge
c. Stir to mix in sugar and milk
d. Spoon porridge into the mouth
e. Repeat step 4 until all porridge is eaten
f. Rinse bowl and spoon
Types of Algorithms
1. Search Algorithms: A search algorithm defines a step-by-step method for
locating specific elements in a data set. For example, a search algorithm could be
used to find Ghana in a list of countries.
Activity 4.2
6
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
2. Sorting Algorithms: These are algorithms that puts elements of a list into an
order, for example, arranging the name cards in alphabetical order.
Activity 4.3
3. Encryption Algorithms: These are algorithms that encode (hide) data to make it
more secure when being stored or transmitted. For example, HTTPS websites that
transmit credit card and bank account numbers encrypt (hide) this information to
prevent identity theft and fraud. These websites will use encryption algorithms.
4. Mathematical Algorithms: These are algorithms that perform mathematical
operations, such as finding the average of two numbers like activity 4 or as
calculating the least common multiple (LCM) of two numbers. Figure 4.3 is
another simple example of algorithm that adds two given numbers and output
the sum. Figure 4.4 shows an implementation of this algorithm in Python.
Activity 4.4
Observe and complete the partially completed algorithm for finding the average
of two numbers.
1. Let the first number be “8”
2. Let the second number be “7”
3. ……………………………….
4. ……………………………….
5. The result “7.5” is the average of the numbers
The completed activity represents a mathematical algorithm.
There are many other examples of algorithms, including those that can solve significant
real-world problems such as optimising traffic flow, financial forecasting, healthcare
diagnostics, and environmental monitoring.
It is important to note that algorithms can be represented in different ways. In this
content, the two ways we will focus on are pseudocode and flowcharts.
7
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Pseudocode
The word pseudo means the opposite of something, therefore the word pseudocode
in a computing environment simply refers to the use of plain text to solve a problem
rather than using code. Pseudocode is an algorithm (a list of instructions) written in a
plain language or text. These instructions need to be in the correct order to complete
a process and the list is read from top to bottom. It is a good practice to number the
instructions/steps as shown in the real-life example shown in Figure 4.3.
8
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Problem specification:
A program is required that will prompt the user to enter three
numbers and will output the product of these numbers.
Write the algorithm for this task in pseudocode.
Pseudocode:
1. Enter first number, number1
2. Enter second number, number2
3. Enter third number, number3
4. Let result = number1 x number2 x number3
5. Output result
Program (written in Python):
numberl = int(input("Enter first number: "))
number2 = int(input(“Enter second number: ”))
number3 = int(input(“Enter third number: ”))
result = numberl * number2 * number3
print(result)
Output:
Enter first number: 5
Enter second number: 4
Enter third number: 2
40
Figure 4.5: A Simple algorithm written in pseudocode
9
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.5
Activity 4.6
1. Produce the pseudocode for the following tasks in the correct order (printed
by the teacher with lines, if applicable) or with the labelled numbers and
share with your colleagues.
a. Calculate the circumference of a circle with radius 5cm.
4
1 2 3
Print circumference = Pi = 3.14159 radius = 5
(circumference) 2 * Pi * radius
10
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
1 2 3
if age = < 18 age = Enter your age: else
5 4
output(age, “You are not eligible to vote.”) output(age, “You are eligible to vote.”)
Congrats on completing these pseudocode activities, next you will learn about
flowcharts.
FLOWCHARTS
While pseudocode uses plain text or language to show the step-by-step approach of
solving a problem, flowcharts also use shapes to solve the same or similar problem. So,
we shall now consider what a flowchart is.
Flowcharts are graphical representations of algorithms that use shapes and arrows
to illustrate the sequence of steps in an algorithm. Each shape represents a specific
action or decision, and the arrows show the flow of the algorithm from one step to
another. Flowcharts can play an important role in displaying information and assisting
reasoning. Using flowcharts, you can visually understand the logic and structure of an
algorithm.
Functions Symbols
11
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Functions Symbols
connector
Off-page
shows that the flow continues on another page. Look
for the matching letter on that page to follow the
process.
12
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Flowchart:
Figure 4.7 is a real-life example showing if a candidate can be admitted to No. 1 High School based on the
condition that the candidate’s total score should be greater than 800.
13
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.7
1. Refer to Activity 4.5 (item 1), to complete the flowchart below as a group in
your books
2. In our book, copy and complete the following flowchart for writing a
program which outputs the sum of four numbers entered by the user.
14
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.8
15
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.9
Problem Analysis
Problem Analysis is the first step in developing a software program. During this phase,
a team member, usually called a systems analyst, talks to the client to understand what
the program is supposed to do. They discuss the purpose of the program, which means
they figure out what the program will be used for. They also identify what the program
needs, such as what data will be input, what processes will be done, and what outputs
are expected. Additionally, any guesses or assumptions made about how the program
will work are clearly stated during this stage.
Example 1
Problem specification: write a program to output the product of three numbers
inputted by the user.
Purpose
A program should be created to allow a user to enter three numbers. The program
should then multiply these three numbers together and output the result.
Table 4.2: Functional Requirements
Assumptions
All numbers that are input will be valid numbers.
16
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Example 2
Problem specification: a program is needed to generate a list of usernames for a class
of 20 pupils given their first names, surnames, and valid ages.
Purpose
A program is to be developed to create usernames for a class of twenty pupils. The
program will ask a teacher to enter the first name, surname, and age of each pupil.
The age entered must be between five and eighteen. The program should output a
list of usernames.
Table 4.3: Functional requirements
20 pupil ages
Assumptions
1. Only 20 sets of details will be entered.
2. The output will link the name of each pupil to his/her username
Design
In the design phase, the information gathered during the analysis phase, such as the
purpose of the software, the main requirements and any assumptions, is used to start
planning how the software will be built. A key part of this planning is creating an
algorithm, which is a step-by-step way to solve the problem. You might remember
learning about different ways to show algorithms, like pseudocode and flowcharts.
During this phase, programmers also make a list of the variables and data types needed
and plan how the user interface (UI) will look.
The user interface is the part of the software that users interact with, such as the screens
where they enter data or see results. When designing these interfaces, programmers
often use wireframes, which are simple sketches that show how the UI will be laid out.
Wireframes can be drawn by hand on paper or drawn using a computer, as shown in
Figure 4.10.
17
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.10
A program is required to calculate the wall area of a room given its length, breadth
and height. Using a design method that you are familiar with, design the UI of
the program.
Share and discuss your design with the class.
Implementation
This phase uses a programming language to write the code to implement the instructions/
steps defined in the algorithm. As we enter the code, debugging may be required.
Debugging means to correct errors in the code. An example of a syntax error (error in in
the spelling or grammar used when coding) is shown in Figure 4:11, where the command
word ‘print’ is incorrectly entered as ‘pront’ so the program will not run correctly.
messagel = “Believe you can and you’re halfway there.” print (messagel)
print(“\n”) #prints a blank line in Python Believe you can and you’re
halfway there. Have a good
message2 = “Have a good day!” print (message2) day!
syntax error
messagel = “Believe you can and you’re halfway there.” pront (messagel)
print(“\n”) #prints a blank line in Traceback (most recent call last):
Python
File “./prog.py”, line 2, in <module>
message2 = “Have a good day!”
NameError: name ‘pront’ is not defined
print (message2)
Figure 4.11: A correct program and the program with a syntax error, each with corresponding outputs
18
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Testing
Testing is an important part of making sure a program works correctly. During the
Testing stage of the Software Development Life Cycle (SDLC), you check if the program
gives the right answers by trying it out with different sets of data.
Testing should be well-planned, and you should keep track of what happens during
each test. It’s also important to test the program in different ways, using normal data
(what you expect), exceptional data (unusual or unexpected data), and extreme data
(very high or very low values).For example, if you’re testing a program that counts how
many students passed a test where a pass is 50% or higher, you might use test scores
like 56, 78, 47, 90, -82, 79, 58, 60, 50, and 77. This includes different types of data to see
how the program handles them.
Normal data refers to data that the program is designed to accept as valid input,
such as the numbers 56, 78, 47, 90, 79, 58, and 77 in the example. When the program
processes this data, it should produce the correct output, like how a score of 90 should
register as a pass.
Extreme data is data that lies on the boundary of what is considered normal, like the
number 50 in the example. A result of 0% or 100% would also be considered extreme
data because they are at the limits of possible outcomes.
Exceptional data is data that is out of range or invalid, like the number -82 or a test
result written as “forty” instead of a number. This type of data is not expected to be
accepted by the program.
In large programs, such as games, bugs can exist because it may not be possible to
test every possible input or action that a future user might make. To test a program
effectively, you should try to manually figure out what the correct output should be
before running the program. It is also helpful to have someone other than the person
who wrote the program test it, as they may spot mistakes that the original coder missed.
Aside from syntax errors (which are mistakes in the code itself), other errors that can
occur during testing are run-time errors and logic errors. A run-time error happens
when a program tries to do something it can’t, like dividing by zero, which can cause
the program to crash. A logic error is a mistake in how the program is designed, such
as using the wrong formula to calculate something, like the circumference of a circle.
After testing and before the software is deployed (making the software available to the
client), installation instructions, user guides, and training materials are created to help
the client use the software effectively. This is part of a phase called Documentation.
After Documentation, there is often an Evaluation phase, where the program is
reviewed to make sure it meets the original problem’s requirements.
19
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Maintenance
After the program is delivered and the client starts using it, the maintenance phase
begins. Maintenance includes fixing any issues that arise during regular use, improving
the program’s design to make it better, or making adjustments for different situations,
like creating a version that works in another country or on a different operating system.
Activity 4.11
1. In your groups, write a program to calculate and output the area of a circle
using a radius value in centimeters entered by the user and taking pi as 3.14
as shown in table 1 (note that ** in Python means exponent in mathematics)
2. Test the program with different numbers (e.g., 4, 12.5, -6 and 0.0014) to test
the program as shown in table below
3. Write your observation in the comment if the programming is correct or
wrong.
4. Correct the program (debug), if needed and test the program again with your
own numbers or with the numbers above.
5. Discuss with your peers why a program needs testing and maintenance.
Table 4.4: Template
Earlier in this course, you were introduced to data and the basic concept of data type as
used in a computing environment. I hope you can recall that data was explained as the
raw fact that can be fed into the computer, which means that a data is not informative
until it is processed or organised. You will now explore data structures and data types,
but before that try your hands on this activity, based on your previous experience:
20
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.12
Study the statement below and answer the questions which follows
10 x 5 = 50
1. Identify the data or data part in the statement above.
2. Where in the above statement will the “processing” be seen or identified?
3. Identify the information (output) in the above statement.
4. Compare your answers with your peers.
DATA TYPES
In computer science, a data type is a label or an element that tells a computer how to
understand and handle a piece of data. We can define data as an elementary value or a
collection of values. For example, an employee’s name and ID may be the data related
to an employee used by a program. A single unit of value is known as a data item. In
the previous example, a data item could be Abena for an employee’s name.
Common examples of data type in programming include integers, floating-point
numbers, booleans, and strings. These types are often abbreviated to int, float, bool, and
str. They are pre-defined data types that are built into most programming languages
and have a fixed size and format.
Note that data types can vary from one programming language to another.
Variables
In the previous lesson, we touched on what a variable is. A variable was explained as a
named location in memory that stores a value of a specific data type. On the other hand,
the data type defines which operations can safely be performed to create, transform
and use the variable in another computation. A variable can have a short name (such
as x and y) or a more descriptive name (such as age, carName or total_volume).
21
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
In some programming languages, a variable has to be declared, indicating its name and
data type, before it can be used. In Python, you do not need to declare variables before
using them. The data item is set to a type when you assign a value to a variable. Some
examples are given in Table 4.5, using a variable called ‘x’.
Table 4.5: Data Types in Python
x = 1961 Int
x = 43.5 Float
x = True Bool
If you want to set a variable to a specific data type, you can do so using type conversion
functions as exemplified below using Python. This means that you can change the
type of a variable’s value to another type by using specific functions known as type
conversion functions.
The point here is that “conversion functions” allow you to convert data from one type
to another. For example, you can convert a number stored as a string to an integer or
change a floating-point number to an integer.
22
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Example 3
int(“123”) converts the string “123” to the integer 123.
Table 4.6: Data Types in Python
x = int(1961) int
x = float(43.5) float
x = bool(True) bool
x = str(1961) str
X = int(43.5) int
Mathematical operations will not work as expected– see Figure: 4.13 below
The decimal part will be truncated.
The Python function type () can be used to check data type. Studying the Python
program and corresponding output in Figure 4.13 will aid understanding how basic
type conversion and the type() function works in Python.
Activity 4.13
1. Individually, write in your books, the data type of each item in the list on the
slide below.
23
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.14
1. Individually, choose a suitable variable name to store the data item in Python
using the same list of data items in Activity 4.13.
2. Compare your answers with a peer and talk about the reasons for your
choices.
Activity 4.15
1. Study the following code and write your prediction on what the output could
be.
Code Prediction
24
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Data Structures
The term “structure” refers to the collection of two or more systems working together
as a whole. For example, the body system such as digestive system, reproductive
system, excretory system, circulatory system and the rest put together is called the
body structure.
Though a single variable can be considered a data structure in the most fundamental
sense, data structures are more commonly understood to be more complex arrangements
that can hold multiple values or collections of data. Data structures are a fundamental
concept in computer science. They are used to organise and store collections of data
in a way that facilitates efficient access and modification. Examples include arrays,
linked lists, stacks, queues, trees, and graphs. These structures can hold multiple items
of certain data type(s), and provide ways to efficiently access, manage, and manipulate
these data items.
Data structures are essential for solving various computational problems and
optimising the performance of algorithms. They are like the building blocks that allow
programmers to efficiently store, retrieve, and manipulate data in computer programs.
25
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
26
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.16
27
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Headmistress
Accountant Chaplaincy
Every item is related to its previous and Every item is attached with many
next item. other items.
Data items can be traversed in a single run. Data cannot be traversed in a single
run.
Examples: Examples:
Array, Stack, Queue, Linked List. Tree, Graph.
28
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
run time, and their size can vary during the code’s execution. The user can change
both the size of a dynamic data structure, and the data elements stored in the data
structure at run time. Examples of dynamic data structures include linked lists,
queues, stacks, and trees.
An array can hold many values of the same data type, under a single name. In the
Python program above (Figure 4:15), the num() array has the name ‘num’ and five
elements of the int data type.
You can access the element in an array by referring to an index number. The first
element in an array has the index 0, so the first element in the num() array can be
referenced by num(0). Arrays will be studied in more detail in the next content.
29
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.17
Data arrangement
Traversing of data
Implementation
Examples
2. Complete the table on linear and non-linear data structures using the given
criteria.
3. Compare your answer with other group and justify your results
Conclusion
Variables, data types, and data structures are three important interconnected concepts
in programming. Variables are containers for data, and their data type defines the kind
of data they can hold.
Data types define the characteristics of the data stored in variables.
Data structures organise and manage variables of different data types, and these
structures are widely used in various applications. There are a variety of data structures
to choose from. Two possible classifications of these structures are linear and non-
linear, and static and dynamic. Data structures enable the efficient storing, retrieving,
and manipulating of data in computer programs.
As we move on in this course, we are building on data structures. Looking at Arrays and
building on from the linear data structures that we looked at in the previous learning.
We will be looking at the types of arrays and their applications in programming.
To picture how arrays work in programming, imagine you are at the Makola or Kejetia
market with a list of ingredients for your favourite Ghanaian dishes—akple, fufu,
kenkey, Red Red, Tuo Zaafi and more. Instead of memorising the list in your head,
you neatly arrange the items on a piece of paper in rows, making it easy to find, add,
or swap items. That is exactly what an array does in programming: It keeps your data
organised and easy to manage, just like your market list.
This learning will help you have knowledge, understanding and application of arrays
in programming languages.
30
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.18
1. You have ten minutes to suggest at least five lists of items of the same type
that a computer program may need to store individually.
E.g., a list of scores obtained by forty-five (45) students in an exam.
a.
b.
c.
d.
e.
f.
2. Share and compare your result with your peers.
Note: Since the items in the list are of the same type and stored in a single line,
we collectively refer to them as an array.
ARRAYS
Arrays are like organised lists (just like you listed in Activity 4.18) where you can store
multiple items of the same type, all in a row in the computer’s memory. Instead of
using different names for each item, you use one name and can quickly find any item
by its position (index) in the list.
In an array, all the data elements share the same name, but each one has a unique
number called a subscript. This number helps you find a specific item in the array by
using the array’s name along with the subscript. One important thing to know about
arrays is that the data is stored in connected (contiguous) memory spaces (locations),
which makes it easy to move (traverse) through the items using their index numbers.
Array variables offer a simpler way to handle multiple values without needing to create
separate variables for each one. For instance, instead of using six different variables to
store the numbers 2, 6, 11, 7, 18, and 4, you can use a single array variable, as shown in
Figure 4.19, to store all these values together.
31
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
If this array was implemented in Python using the array variable name “numbers”, the
code in Figure 4.20 could be used. Print statements are included to show how array
indexing works.
numbers = [2,6,11,7,18,4]
[2,6,11,7,18,4]
print(numbers) 2
\n 4
print(numbers[0])
print(numbers[5])
Figure 4.20: Numbers program, version 1- sets up an array of six integers and outputs the array and two
elements
Other examples of how arrays can be used instead of declaring multiple variables
include:
Instead of having separate variables for each student’s score such as
score1 = 75, score2 = 88, score3 = 92, etc.
You can use a single array called scores to store all the values together
scores = [75, 88, 92, 67, 84]. This is an integer array.
Also, storing Names of Friends can be done as friends = [“Ama”, “Kwame”, “Kojo”,
“Akua”, “Yaw”] instead of having individual variables for each friend’s name,
like friend1 = “Ama”, friend2 = “Kwame”, etc. This variable is a string.
Another example of an array containing string elements is shown in Figure 4.21. In
this array, two of the elements are empty strings. The second print statement includes
text to label the output. In Python, the ‘#’ symbol is used to write comments. If you
want to include notes or explanations in your code that should not be executed, you
can start the line with a ‘#’ symbol.
Cat
The first animal stored
in the array is Dog
32
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Arrays are often used in different situations to organise and store lists of related
information that are all the same type. For example, imagine you have a shopping list
with items like tomatoes, rice, and fish (these are all strings). Instead of using separate
variables for each item, you can store them all in one array. Similarly, you can use an
array to keep track of the names of students in your class (also strings), the number
of goals your school’s football team scored in 12 matches (integers), the yes or no
answers from 20 people in a survey (booleans), or the money collected by a charity in
five different churches (floats). Arrays help you organise this data in a way that is easy
to manage and use.
Activity 4.19
Let’s look at Array Size and Indexing: In most programming languages, the size of an
array declared as arrayName(size) indicates the total number of elements it can hold,
directly corresponding to the number specified. For example, if you declare score(9),
it means the array score can hold exactly 9 items, indexed from 0 to 8 in languages like
Python, C++, and Java.
For example, in Figure 4.17 and Figure 4.18, the arrays for numbers and animals could
be referred to as numbers(6) and animals(4).
Activity 4.21
1. Individually, find out the number of items these arrays can hold
a. Grade[23]
b. Food[19]
c. Score[54355]
d. Houses[6, 4]
e. Teachers[1021, 13, 40, 45, 60]
2. Justify your findings with a reason
3. Compare your answers to your peers.
33
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
numberl = 2
number2 = 6
2,6,11,7,18,4
number3 = 11
2
number4 = 7
4
number5 = 18
number6 = 4
print(numberl, number2, number3, number4, number5, number6)
print(numberl)
print(number6)
Figure 4.22: Numbers program, version2– uses six different variables to store six integers
Activity 4.21
Using your response to Activity 4.18, suggest a suitable data type and array
variable name for use in a Python program.
E.g.: The type and suitable namee for the example given in Activity 1 could be
float and exam_score (44). Think about your responses and how they could
be improved if needed.
34
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Figure 4.23: An integer array variable called “arr” with five elements.
35
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Parallel arrays use multiple arrays to represent related data, where each index in
one array corresponds to the same index in the other arrays. For example, if you
have one array for names and another for ages, the elements at the same index
in both arrays represent the same person. So, if `names[5]` is “RaF” and `ages[5]`
is 12, this means RaF is the sixth person and she is 12 years old, as illustrated in
Figure 4.25. This approach allows you to store different types of related data using
arrays.
ages 12 13 12 14 13 12
Figure 4.25: A set of two parallel arrays
2. Two-dimensional array: This type of array has multiple rows and columns,
forming a grid-like structure. For example, a two-dimensional array with three
rows and four columns, as shown in Figure 4.26, can be visualised as a table. Each
element in the array is accessed using two indices: one for the row and one for the
column, typically denoted as (r, c). The value at a specific position is determined
by these two indices, where “r” represents the row number and “c” represents the
column number.
In reading the table or 2D array, you read the row then the column. For example,
(Row, column) is …
1. (0, 2) is 3
2. (1,1) is 11
3. (2, 0) is 19
36
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
A 2D array offers a more efficient way to manage related data compared to parallel
arrays, but all elements must be of the same type.
For example, if a school wants to store the marks of five students (Daniel, Kojo,
Beatrice, Nii, and Nana) across four subjects (Computing, Science, Mathematics,
and English), you will use a 2D array. This array would have four rows (one for
each subject) and five columns (one for each student), organising the marks in a
tabular format. Each cell in this table represents the mark a student received in a
particular subject.
Computing 10 55 90 70 60
Science 50 60 75 65 95
Mathematics 95 75 55 85 45
English 35 95 65 55 75
Figure 4.27
Activity 4.22
37
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
After writing the code, we noticed the total marks for Beatrice in Science is to change
from 75 to 92.
Instead of rewriting the marks code all over, we can just update Beatrice’s marks. Let’s
do this as an activity together.
Activity 4.23
1. Using a Python environment, copy the code in Figure 4.28. (Optional: Click
“here” to access a sample environment).
2. Identity the index of Beatrice’s Science score.
3. Write the Python program for the update using this guide “marks[row_index]
[column_index] = 92”.
4. Run the code
5. Confirm the update by writing the code “print([row_index][column_index])”
6. Alternatively, confirm the update by writing the code “print(marks).
38
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.24
Complete this list by adding onto the applications of 2D arrays. Ensure to add at
least three items with explanation and examples.
1. Representing Data in Tables: Just like the marks sheet your teacher uses
to record scores in different subjects, you can use a 2D array to represent this
data. For example, a 2D array can store the marks of students across various
subjects, like a spreadsheet or table (as shown in Figures 4.25 and 4.26).
2. Game Boards: Think of a game like Ludo or Tic-Tac-Toe. The board can
be represented using a 2D array, where each cell corresponds to a specific
position on the board. For example, a chessboard, which is 8x8, can be
modelled using a 2D array.
3. Computer Graphics and Images: Imagine you are editing a photo on
your computer. Each tiny square (pixel) in the image can be stored in a 2D
array, with the array holding the colour information for each pixel. Image
processing, such as applying filters or adjusting brightness, often involves
manipulating these pixel values stored in 2D arrays.
4.
5.
6.
39
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.25
Write at least three additional advantages and three disadvantages of the array
data structure and present your findings to class orally.
Have you ever played a game that connects you from one level to another level as you
win?
If your answer is No then do this activity for 15 minutes
Activity 4.26
1. Click this link to play code combat on the internet (ensure you have access to
the internet before playing).
2. Click on start level after the game is loaded as shown in Figure 4.29.
40
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Figure 4.29
3. Use the same codes as seen in the image below to instruct your hero avatar to
move in the directions and pick up the gem.
Figure 4.30
Figure 4.31
41
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Wow congratulation, you have done a lot in this activity, you coded in Python,
and you also learnt more about arrays.
A linked list is not fixed like an array, the size of a linked list can be changed anytime,
making it dynamic.
42
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.27
1. Use Figure 4.32 as a guide to draw illustrations for both the deletion and
addition of nodes in the linked list.
2. Show your illustrations to your peers for improvement if needed.
Activity 4.28
1. Based on your understanding of singly and doubly linked list, draw two
illustrations to represent them.
Use Activity 4.26 as a guide to help you.
2. Observe your illustrations and give 1 advantage and 1 disadvantage between
singly and doubly linked list.
In addition to the advantage and disadvantage identified in Activity 4.27, doubly linked
list has the advantage of allowing elements to be passed through in two ways. While
singly linked lists allow elements in only one way. One disadvantages of doubly linked
lists include greater memory requirements (two pointers rather than one pointer per
node) and more code is required for implementation, while a singly linked list needs
lesser memory and less code for implementation.
Activity 4.29
With your peers, list at least four additional applications of linked lists.
1. For GPS guidance systems, linked lists can be used to store and organise a list
of places and routes that make it easy for users to get where they want to go.
2. Because a web browser’s search results are linked together as a linked
list, you can access the previous and next URL by using the back and next
buttons.
43
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
3. The songs in the media player app are connected to the songs that came
before and after them; using a doubly linked list.
4. …………………………………………………………………………………………….
5. …………………………………………………………………………………………….
6. …………………………………………………………………………………………….
7. ……………………………………...……………………………………………………..
8. …………………………………………………………………………………………….
Let us now discuss the advantages and disadvantages of Linked Lists in general.
44
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.30
Let us explore by observing the process of how stacks work in the illustration
below. Note that “SP” means Stack Pointer.
Answer the following questions based on your observation.
1. Identify how many elements are in the initial state of the stack.
45
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
2. Write your thought on why the SP at the initial state is below the bottom.
3. Use the appropriate terminology to explain what happened between the
middle diagram and the last diagram on the right.
Good work finishing the activity, it is important to know that stacks can be made using
different types of memory like:
1. Contiguous Memory: This is like an array where all the items are stored side by
side.
2. Non-Contiguous Memory: This uses a linked list where each item can be stored
in a different place, but each one points to the next.
Again, as new data is added to the stack, it cannot go past the End pointer. If it does,
there is a ‘Stack Overflow’ and the program ends. Also, data must not be popped
(removed) below the Bottom pointer. If it does, there is a ‘Stack Underflow’ and the
program ends.
Activity 4.31
46
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.32
With your peers, list at least two additional advantages and disadvantages of
stacks
Advantages of stacks
1. Stacks are a simple data structure that is easy to understand, which means
they can be used in many situations.
2. Stacks use the LIFO principle to make sure that the first thing taken off the
stack is the last thing added to it. There are many times when this behaviour
is important, like when a program calls a function.
3.
4.
Disadvantages of stacks
1. You can only get to the elements at the top of a stack, which makes it hard to
get to or change elements in the middle of the stack.
2. If more elements are pushed onto a stack than it can hold, an overflow error
will occur, resulting in a loss of data.
3.
4.
47
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.33
Figure 4.36
Congrats, you have just learnt about linked lists and stacks.
48
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
What is a Queue?
Queue simply means being in a line, just like how the papers were in line waiting to
get ink printed on them. In computing, data or tasks line up to be processed. A queue
is this line of items waiting to be handled.
A queue is similar to a stack because both involve adding and removing elements.
However, in a queue, you add elements at one end and remove them from the other
end. This method is called FIFO, which stands for First In, First Out. It means the first
item that goes into the queue is the first one to come out.
We also need to know that in computing, queues can be implemented using arrays or
linked lists, both of which you have studied earlier in the course.
A real-life example of a queue is a line at a voting booth or a ticket counter as shown
in images below.
49
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.34
1. In five minutes, write a list of at least ten (10) real-life examples of queues,
together with your colleagues.
2. Explain with reasons, why any of your listed examples in (a) is a queue but
not a stack.
Applications of Queues
In addition to your list, some applications of queues are:
1. Printer Queues: Printers use a system called queues to manage print jobs. When
you send a document to be printed, it joins the end of this line, and the printer
tackles each job sequentially.
2. Task Scheduling: Queues are employed to organise tasks by order or priority.
For example, a task management system might use a queue to ensure that high-
priority tasks are addressed promptly.
3. Operating Systems: Operating systems utilise queues to keep track of tasks that
need processing. This helps manage the computer’s resources effectively, such as
distributing CPU time among various programmes.
4. Traffic Management: Just as with managing road traffic, systems like airport
controls use queues to regulate the flow of vehicles and people, ensuring smooth
and safe movement.
5. Network Protocols: Protocols like TCP employ queues to sort data packets for
transmission over the internet. This ensures that messages are sent and received
in the correct order.
6. Computer Memory: Some types of computer memory use queues to order the steps
required to execute programs. This process starts with fetching an instruction,
then decoding, and finally executing it. New instructions join the back of the
queue to await their turn.
50
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Well done, we have covered content on Queues and Linear Data Structures. Let’s now
look at what non-linear data structures are and how they are used in computing.
Activity 4.35
1. Watch this video (click on the word “video” to access it) to deepen your
understanding of non-linear data structures. Do not worry if you do not
understand the calculation, it will be covered in detail in year 2.
2. Draw a diagram illustrating what a tree and graph are in your books.
3. Write beneath the diagrams a brief note of what trees and graphs are.
4. Write a brief key difference between graphs and trees.
Graphs
A graph is a collection of nodes with data elements that are connected to each other
nodes by lines (edges). The nodes can also be referred to as vertices.
Trees
A tree is a non-linear hierarchical data structure that organises and stores data in a
way that allows for efficient navigation and searching. It consists of nodes with data
connected by edges, forming a branching structure.
One use of a graph structure is to model relationships between users of social media
platforms like Facebook and X. The users are represented as nodes, and friendships or
connections between them are represented as edges. – see Figure 4.39
51
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Now that we have studied both linear and non-linear data structures, let’s compare
them.
Activity 4.36
1. In your books, draw two large bubbles or boxes. Label one “Linear Data
Structures” and the other “Non-linear Data Structures.”
2. From the “Linear Data Structures” bubble, draw lines to make smaller
bubbles or boxes and label them with examples like “Arrays,” “Queues,” and
“Stacks.”
52
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
3. From the “Non-linear Data Structures” bubble, do the same for examples like
“Trees” and “Graphs.”
4. Next to each example, write a short description or key characteristic of them.
5. Write at least two key differences and similarities between linear and non-
linear data structures below your drawing.
6. Once you have completed your concept map, show it to your teacher for
approval.
7. After your teacher checks your map, discuss it with your classmates. Share
what you have learnt and see what interesting points others have in their
maps.
Beautiful, you have successfully compared the linear and non-linear data structures.
In addition to what you drawn and written, it is important to note that when choosing
between linear and non-linear data structures, consider factors such as memory usage,
access time, insertion and deletion, and search and sort capabilities.
Linear data structures typically use less memory than non-linear data structures but
have slower access time, often due to their fixed size and structure.
Non-linear data structures may have faster access time, but they require more memory
to store pointers or references.
Hello learner, as we progress with SDLC, in this learning, our focus will be on its last stage,
the implementation stage/phase of the cycle. It involves planning and implementing
the algorithm, flowchart and pseudocode as a program, using programming languages
such as Python, etc. Get ready for such fun!
An introduction to Python
There are many programming languages, like Python, Java, C#, and Swift. Python
is very popular and can be used for many different things. It is called a high-level
programming language, which means its code looks a lot like the English we speak,
making it easier to understand and learn, meaning beginners can pick it up quickly.
53
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
For example, the Dropbox desktop app is written entirely in Python, showing how
Python can work on different types of computers and operating systems. Its ability to
run on various platforms makes it a popular choice for many businesses.
54
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
3. Start coding!
a. print () function is an in-built function in Python to output (display) specific
messages to the screen.
To print a blank line, use the following command(s):
print () or print(“\n”).
An example of print is shown below.
Activity 4.37
1. Individually, download your chosen Python IDE to your device and install it
using the steps above.
2. Create a folder location where you would like to keep your python programs
(applicable to laptops).
3. Create and open a new Python project
4. Copy the following python code into your Python IDE and see the output:
a. print(“My name is …………….”) # Type your name in the dotted space.
b. print(“I am ………. years old”) # Type your age in the dotted space.
5. Now, write your own python code to display your aggregate and the name
of your basic school.
6. Share your result to your peers.
Congrats, you have just completed your first python coding activity.
55
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
b. Assignment operator
The assignment operator in Python is the “=” symbol.
For example,
i. age = 16.
ii. reply = True.
iii. cost = 34.56.
iv. city = “Kumasi”.
v. console = ‘PlayStation’.
Note that single-quoted strings (‘ ’) and double-quoted strings (“ “) should both
work in most Python editors.
See Figure 4:41 on how the assignment operator is used in labelling in Python.
Python is fun
My message to you is Python is fun
Eric Asomani Asante won the 2020 Ghana
Teacher Prize Award
Activity 4.38
56
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
c. Arithmetic operators
The equality comparison is defined in Python with a double
Table 4.9: Arithmetic operators
Maths Python
= ==
≠ !=
< <
> >
≤ <=
≥ >=
The above code exemplars should enable you to now code simple sequence programs,
that is, programs that consist of a simple input, a process, and the output steps. We
will now move on to focus on the implementation of algorithms, involving simple
sequences using the Python programming language.
57
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.39
1. Correct the errors in the following lines of code. These errors could be syntax
or logical. Two examples are:
a. size = input(“Enter your shoe size)
b. average = (number1 + number2)/3
2. Correct the errors in the following Python programs.
print “Enter your favourite colour: “ colour = inputt()
print(“Hello there”)
print(colour “is a nice colour”)
Activity 4.40
1. Follow the below steps to write a program that asks the user for their name
and then greets them.
a. Use the input() function to prompt the user for their name.
b. Store the input in a variable called name.
c. Use print() to display a greeting that includes the user’s name.
2. Follow these steps to create a program that asks the user for their favourite
movie and why they like it.
a. Ask the user for the name of their favourite movie.
b. Ask why they like that movie.
c. Combine and display the responses in a complete sentence.
Note an alternative for writing this activity using f-string in the print function is
as follows:
movie = input(“What is your favourite movie? “)
reason = input(“Why do you like it? “)
print(f”Your favourite movie is {movie} because {reason}.”)
The f-string (formatted string literal) is a way to embed variables and expressions
inside of a string. In Python, you create an f-string by placing the letter f before
the opening quotation mark of the string and the variables are wrapped in braces
{ } within the statement to be output.
58
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Input-Process-Output Model
A computer program using the input-process-output model receives inputs from a user
or other source, does some computations on the inputs, and returns the results of the
computations. Before a program can be coded, it needs to be designed. Part of the
design process, as we have seen already, is to create an algorithm to solve the given
problem. Inputs are the information you get to use to solve the problem. Processes are
the steps needed to get the output results from the input stage. Outputs are the goal of
the problem solution.
Activity 4.41
1. Write code to output ‘Happy Birthday’ three times, separating each Happy
Birthday message with a blank line.
2. Write two similar pieces of code to output repeated messages of your own
choosing, as practiced in (a).
3. Show the result to your peers and discuss.
Activity 4.42
59
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.43
1. For each example, rearrange the lines of code to match the given pseudocode.
Note that the operator to represent exponent in Python is **, so print(10 ** 3)
would output 1000.
Pseudocode
a. Let x equal 2
b. Let p equal 5
c. Calculate the value of xp
d. Output the value of xp
Table 4.10: Code
p=5
#Output answer
x=2
answer = x**p
60
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
2. Enter the re-arranged code and run it to check that it gives the expected
answer.
Table 4.11: Re-arranged code
Algorithms Implementation
Algorithm implementation refers to the process of translating an algorithm’s logical
steps and instructions into actual code that can be understood and executed by a
computer. This process involves writing code, in a suitable programming language, to
achieve the desired functionality described by the algorithm.
The step-by-step guide in implementing an algorithm in Python is discussed below.
1. Understanding the algorithm:
Make sure you fully understand the steps of the algorithm that you are trying to
implement. The design of the algorithm can either be broken into smaller parts
(modular) or kept as one big part (non-modular). It is recommended that, as new
coders, you start with the non-modular approach.
61
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
At this point, it is a good idea to do a “dry run” of the algorithm. This means that
you as the programmer, should manually go through the algorithm using a pen
and paper to track how the values of the variables change, to ensure everything
works as expected.
2. Translating the algorithm steps to code:
a. If needed, break the algorithm down into smaller parts.
b. Write Python code that matches each step, using the right programming tools.
These tools include simple sequences (one step after another), decisions/
selections (if statements), loops (repeating steps), and functions. If your
algorithm needs data structures such as arrays or stacks, make sure to include
them in your code.
c. Handling inputs and outputs: Write code that manages the inputs needed by
the algorithm. You can use the assignment operator (=) for storing values, the
input() function to get input from the user, and the print() function to display
results. You can also read and write data from a file in Python, using special
file-handling functions.
3. Creating a new Python file: Open your chosen IDE and create a new Python
file. Type your code into the file. To make your program easier to understand, use
clear and meaningful variable names, add some spaces between the lines of code
(whitespace), and include comments (using the ‘#’ symbol) to explain what your
code is doing. Finally, save your program with a good file name in the folder where
you keep your Python files.
4. Testing and debugging: Test your code using different sets of data to make sure
it gives the correct results. You have already learned how to create good test data
sets in earlier learning. The coding environment (IDE) you are using has built-in
tools to help you find and fix any mistakes (debugging).
5. Optimisation and refinement: Take time to review your code and look for ways
to make it run faster (optimize performance), how to make it easier to understand
(improve readability), and to get rid of any parts that are not needed (remove
unnecessary code or comments).
6. Code review and feedback: If applicable, share your code with your peers or
mentors for code review. Feedback can help you enhance your implementation
and overall solution to the algorithm.
7. Integration (if applicable): If your algorithm is part of a bigger application or
project, make sure to properly integrate (connect) your Python code with the rest
of the project where it is needed.
8. Deployment (if applicable): If your code is part of a software product, make
sure it is properly set up (deployed) and works as expected in the real-world setting
where people will use it (production environment).
62
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Implementation Exemplars
Example 1 – a simple maths algorithm
We have already seen this algorithm, both in pseudocode and as a flowchart in our
earlier learning.
Pseudocode
1. Assign x the value 529 x = 529
2. Assign y the value 256 y = 256 785
3. Assign z the sum of x and y. z = x+y print(z)
4. Output the value of z
Flowchart
63
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.44
64
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.45
65
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.46
Do this activity in pairs. A pair forms a team for this activity. Each team gets two
items (e.g., a pen and a pencil) and a basket or bowl that will act as a temporary
location (Temp) for storing one item during the swap. Each team starts with the
two distinct items.
For example: student A holds a pen while student B holds a pencil.
Let us begin:
1. On your facilitator’s signal (“Ready, Set, Swap!”), swap the items using the
following steps:
Step 1: Student A puts their item (pen) in the basket (Temp).
Step 2: Student A takes the item from Student B (pencil).
Step 3: Student B takes the item from the basket (pen).
2. The first pair to successfully swap the items without confusion wins the
round.
NB: Each team will be timed, and the fastest team wins the competition.
66
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
The activity you just performed is called swapping. Let us look at swapping in more
detail.
2. Manual Swapping
Imagine you and your friend each have a piece of fruit. You have an orange, and
your friend has a mango, but you both want to swap fruits.
How do you swap your fruits without mixing them up?
Since you do not want to drop the orange or mango, you get an extra basket
called Temp to hold one fruit temporarily.
Put your orange into the extra basket, take the mango from your friend and hold
it, now, let your friend take the orange from the basket.
This scenario and the steps you used to swap the pen and pencil in Activity 46
show how manual swapping is done.
In programming, this would be the code to swap two variables manually:
Temp = A # Step 1: Store A (Orange) in Temp
A=B # Step 2: Move B (Mango) to A
B = Temp # Step 3: Move Temp (Orange) to B
Activity 4.47
1. Using one hand, demonstrate how you will swap these two items: fufu and
banku.
2. Write the ordered steps you used to do the swapping in your jotter.
3. Share your notes with your peers.
67
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
It is important to note that the names of the variables in the code can be different from
those used when explaining the algorithm. In the example provided, the names are the
same but are written in different cases. For example, in Python, it is common practice
to use lowercase letters for variable names. This helps maintain readability and follow
Python’s naming conventions.
68
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Figure 4.46 shows a slightly different version of this algorithm where the user enters
the two values to be swapped. The corresponding code and the output from a test run
are also shown.
If you are familiar with subroutines (or functions) in Python, you can experiment
with creating a swap function to swap the values of two variables. In the example
shown in Figure 4.47, you can define a function called swap that takes two variables, A
and B, as inputs, swaps their values, and then returns them.
69
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
The swap algorithm is a fundamental concept in programming that plays a key role in
many tasks. It is used to exchange the values of two variables, and this simple operation
is critical in several areas of computing, including: Sorting Algorithms such as the
Bubble Sort and the Quick Sort, Data Manipulation, and Variable Swapping tasks.
Activity 4.48
1. Design and code a program that will swap two string variables using:
a. A flowchart,
b. Pseudocode,
c. Python code.
70
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.49
Activity 4.50
1. Write a Python program that swaps the values of two variables without
using a temporary variable, using arithmetic operations.
2. Share the result with your peers and teacher.
71
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Problem: Takoradi Mall is giving a discount coupon to anyone who is below 15 years
old. Find out if someone is eligible for a discount ticket.
Decomposing this problem, gives:
1. Find out how old the person is.
2. If the person is younger than 15 then say, “You are eligible for a discount coupon.”
3. Otherwise, say “You are not eligible for a discount coupon.”
To convert the flowchart or pseudocode into a program, look at each individual step,
and write an equivalent instruction. Sometimes, the steps will not match exactly, but
they will be fairly close.
Coding:
age = int(input(“How old are you?”)) #we use int()
function to convert the string into an integer
if age < 15: # checking if correct age for a discount
ticket
print(“You are eligible for a discount.”)
else:
print(“You are not eligible for a discount.”)
Run 1 output:
How old are you? 26
You are not eligible for a discount.
Run 2 output:
How old are you? 13
You are eligible for a discount.
Note that lines 1, 2, and 3 of pseudocode have been combined into one input() statement.
72
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.51
1. You are at a local provision store at Krofrom and you want to buy a snack.
Write pseudocode and a Python program for this condition: if you have GH¢5
or more, you will buy a meat pie and if you have less than GH¢5, you will buy
a bofrot.
2. Show the result to your facilitator and peers for feedback.
3. What better way can you write the Python code to get same result? (note, this
is called refactoring your code to provide improvements)
Activity 4.52
Hello learner! We are sure your excitement for this course keeps growing as we move
forward. This time, we will look at implementing and manipulating 1D arrays and
built-in (array) list methods in Python.
Activity 4.53
1. Reflect and write a short note on what you remember from the lesson on data
structures.
73
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
2. Complete Table 4.11 to give a suitable description, name and data type for the
set of array descriptions.
Table 4.11: Array descriptions
ARRAYS IN PYTHON
In our earlier learning, we looked at how an “array” is one of the most fundamental
data structures in any programming language. You learnt that the elements in an array
data structure are arranged on a straight path or has an ordered collection of items of a
single type. Python does not have a native array data structure, so the list data structure
is used in Python to implement arrays.
A list is simply a sequence of values stored in a specific order with each value identified
by its position in that order.
74
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Python lists can contain duplicate values as seen in Figure 4.39 below. “Apple” appears
twice in the array.
Please note that as we progress through this learning, we will use the term ‘array’
instead of list.
You already know how to reference a particular element in an array as we covered that
earlier in our learning – we use the index of the element.
For example, if the array in Figure 4.48 was called numbers, then the code print
(numbers[1]) would output 3.
To be able to code and fully manipulate arrays in a Python program, you need to
understand the terms ‘iteration’ and ‘selection’ in programming. These will be covered
later in your learning. For the time being, we will use in-built codes called functions
and methods for the implementation of algorithms that use arrays. This will make the
algorithms very straightforward and most of the coding will be done for you.
Array length
To determine how many items an array has, we can use the len() function – see
Figure 4.39.
75
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Figure 4.50: Checking out how Sort () method works in the Python console/shell
76
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Algorithm
1. Set up an array with the names of 5 daily activities.
2. Use an in-built method in the programming language to reverse the order of
the elements in the array.
3. Output each element in the re-ordered array, one element per line.
Code Output
Activity 4.54
Plan and write a program that set up an array of seven activities of your choice
that happen in the school without duplicating any of the element.
1. Write an algorithm for the planned activities.
2. Use in-built Python code to reverse the order of the elements in the array.
3. Print each element on a separate line.
4. Work with a peer to come up with a more efficient way algorithm to give the
same output and discuss as a group.
77
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Algorithm
1. Set up an array with the given elements.
2. Set up two types of computers to check for – tablet and mainframe.
3. Use an in-built method in the programming language to find the number of
occurrences of the two types in the array.
4. Output the number of occurrences of each type to be checked in the array.
Code Output
Activity 4.55
78
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Code Output
Activity 4.56
1. Create a list of your favourite books and make a copy using the copy()
function.
2. Create another list of your hobbies and make a copy using the list() function.
3. Write a program that duplicates a list of your favourite foods using list slicing
‘[:]’.
4. Write your observation of using the copy() function, the list() function and
slicing ‘[:]’.
Example: swap array algorithm
The swap array algorithm normally swaps the positions of the elements in
an array. For instance, if you have an array [1, 2, 3, 4] and want to swap
the first and last elements:
Before: [1, 2, 3, 4]
After: [4, 2, 3, 1]
79
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
Activity 4.57
Copy and complete the code below and complete it to that the variable values are
swapped
# Original variables
student1 = “Gyampo”
student2 = “Daniel”
print(“Before swapping:”)
print(“Student 1:”, student1)
print(“Student 2:”, student2)
# Swapping using a temporary variable
temp =
student1 =
80
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
student2 =
print(“\nAfter swapping:”)
print(“Student 1:”,………...)
print(“Student 2:”, ……….
81
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
82
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
83
EXTENDING READING 4.8
• Research how arrays (lists) can use used in Python to implement the following
data structures: a stack, a linear queue and a linked list. Use your research findings
to implement one of the listed data structures using an array.
• Click here or https://www.youtube.com/watch?v=6a39OjkCN5I to watch a video
on array implementation in Python.
• Chan J., (2014). Learn Python in One Day and Learn It Well Python for Beginners
with Hands-on Project. The only book you need to start coding in Python
immediately. Page 7 – 54.
• OpenStax (2024) Introduction to Python Programming retrieved from https://
openstax.org/books/introduction-python-programming/pages/1-1-background
on 11/09/2024, page 7-37.
• Park A. (2022) - Python Programming for Beginners: The Ultimate Crash Course
to Learn Python in 7 Days with Step-by-Step Guidance and Hands-On Exercises.
ISBN 13: 9798836767464
84
Review Questions
85
Reviewed Questions 4.2
1. Explain the role of the client at the Analysis stage of SDLC.
2. Some software development models are considered iterative. This means that an
earlier stages in the development process can be revisited and changes made if
required when new information becomes available. Describe how this may be
true using the following stages:
a. Testing and Design
b. Design and Analysis
2. As a Year 1 Computing learner, you are tasked to store data for the seating plan for
your class, write a Python code for the seating plan.
86
Review Questions 4.6
1. Recommend a data structure for each of the following applications. In each
instance, give at least one reason for your choice of structure:
a. CPU task scheduling.
b. Reversing a list of stored characters.
c. Storing a song playlist to play previous and next song.
2. Explain why a programmer would choose a contiguous memory data structure to
implement a queue rather than a non- contiguous memory structure.
87
Review Questions 4.8
1. Create an array called family in Python that, when output, will give:
[‘Father’, ‘Mother’, ‘Son’, ‘Daughter’]
a. Write the line of code that must be added to update the first element to
‘Grandpa’.
b. Write a line of code that will print the third element in the array.
c. Write one line of code that will sort the family’s array elements into alphabetical
order
d. Test these lines in the Python IDE environment to check your answers.
2. Design a program that will:
a. create an array called subjects consisting of three school subjects to be inputted
by the user.
b. swap the first and last subject element.
c. output two versions of the array – the original order and then the order after
the swap.
88
Answers to Review Questions
89
The final value of `SUM` is printed.
The algorithm ends with the `END` symbol.
d. working:
Iteration N SUM
1 1 3+1=4
2 2 4+2=6
3 3 6+3=9
4 4 9+4=4
5 5 13 + 5 = 18
90
Static Data Structures: Dynamic Data Structures:
• Size Fixed at Compile Time: The size of • Size Can Change at Runtime:
a static data structure is determined when The size of a dynamic data
the program is compiled and cannot change structure can grow or shrink during
during runtime the execution of the program,
depending on the amount of data
being stored
Examples
91
[None, None, None, None] # Row 4
]
92
• Reason: A stack operates on a Last In, First Out (LIFO) principle, which
is ideal for reversing sequences. Characters pushed onto the stack will be
popped in the reverse order of their original arrangement.
c. Storing a Song Playlist to Play Previous and Next Song
• Data Structure: Doubly Linked List
• Reason: Doubly linked lists allow for easy traversal both forwards and
backwards, which is necessary for navigating between previous and next
songs in a playlist.
2. Imagine a line at a bus stop. Each person in the line is like an element in a queue.
In computing, we can store these elements in memory.
There are two ways to store them:
• Linked List: This is like a chain of people holding hands. Each person knows
the person in front and behind them.
• Contiguous Memory: This is like everyone standing side by side in a row.
Why choose contiguous memory for queues?
• Faster: It’s like jumping directly to a person in the line without having to count
from the beginning.
• Simpler: It’s easier to manage people standing in a row than a chain of people
holding hands.
• Predictable: You know exactly how many people can fit in the line.
• So, while linked lists are flexible, contiguous memory is often a better choice
for queues because it’s faster, simpler, and more predictable.
93
Manufacturing cost: manufacturing_cost (float, calculated)
Profit: profit (float, calculated)
c.
# Input values for costs and selling price
water_cost = float(input(“Enter the water cost per litre: “))
flavouring_cost = float(input(“Enter the flavouring cost per litre: “))
labour_cost = float(input(“Enter the labour cost per litre: “))
selling_price = float(input(“Enter the selling price per litre: “))
# Calculate manufacturing cost
manufacturing_cost = water_cost + flavouring_cost + labour_cost
# Calculate profit
profit = selling_price - manufacturing_cost
# Output the results
print(f”Manufacturing cost per litre: GH¢ {manufacturing_cost}”)
print(f”Profit per litre: GH¢ {profit}”)
2. Step-by-Step Algorithm:
i. Start
ii. Store the value of number1 in a temporary variable, temp.
iii. Assign the value of number3 to number1.
iv. Assign the value of number2 to number3.
v. Assign the value of temp (which holds the original value of number1) to
number2.
vi. End
3. Steps to Design the Program:
The user inputs the amount in Ghana Cedis (GH¢) to be converted.
The user also inputs the exchange rate (how many CFA one GH¢ is worth).
The program performs the conversion using the formula: CFA amount = GH¢
amount × exchange rate.
The program outputs the equivalent amount in CFA.
94
The code is:
# Input the amount in GH¢ to be converted
gh¢_amount = float(input(“Enter the amount in GH¢: “))
# Input the exchange rate (1 GH¢ to CFA)
exchange_rate = float(input(“Enter the exchange rate (GH¢ to CFA): “))
# Calculate the amount in CFA
cfa_amount = ghc_amount × exchange_rate
# Output the result
print(f”{ghc_amount} GH¢ is equivalent to {cfa_amount} CFA at an exchange
rate of {exchange_rate}.”)
4. The Simple Interest Code:
# Input the principal amount (P)
P = float(input(“Enter the principal amount (P): “))
# Input the rate of interest per year (R)
R = float(input(“Enter the rate of interest per year (R): “))
# Input the time in years (T)
T = float(input(“Enter the time in years (T): “))
# Calculate the simple interest using the formula I = (P * R * T) / 100
I = (P * R * T) / 100
# Output the calculated simple interest
print(f”The simple interest on a loan of GHS {P} at a rate of {R}% for {T} years
is: GHS {I}”)
5.
# Input the three numbers
num1 = float(input(“Enter the first number: “))
num2 = float(input(“Enter the second number: “))
num3 = float(input(“Enter the third number: “))
# Calculate the sum of the numbers
sum_of_numbers = num1 + num2 + num3
# Calculate the average of the numbers
average = sum_of_numbers / 3
# Output the sum and the average
print(f”The sum of the numbers is: {sum_of_numbers}”)
print(f”The average of the numbers is: {average}”)
95
Answers to Review Questions 4.8
1.
a. Creating the array ‘seasons’
family = [‘Father’, ‘Mother’, ‘Son’, ‘Daughter’]
b. Updating the first element to ‘Grandpa’
family[0] = ‘Grandpa’
c. Printing the third element in the array
print(family[2])
d. Sorting the seasons array in alphabetical order
family.sort()
print(family)
2. Code
subjects = []
for i in range(1,4):
subject= input(f”Enter subject{i}: “)
subjects.append(subject)
print(“Original array:”, subjects)
temp = subjects.copy()
subjects[0], subjects[-1] = temp[-1], temp[0]
print(“Array after swapping first and last elements:”, subjects)
96
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
REFERENCE
• Alan D., Barbara H. W., Roberta M. R., (2012) System Analysis and Design, pages
10 – 17, 5th Edition, VP & Publisher.
• Blogs, B., & Software. (2022, September 8). 4 steps of a successful software
development life cycle. Vates. https://www.vates.com/4-steps-of-a-successful-
software-development-life-cycle/
• Brad M., David R. (2013) Problem Solving with Algorithms and Data Structures,
Release 3.0, pages 3 – 116.
• Chan J., (2014). Learn Python in One Day and Learn It Well Python for Beginners
with Hands-on Project. The only book you need to start coding in Python
immediately. Page 7 – 54 retrieved from https://www.pdfdrive.com/a-python-book-
beginning-python-advanced-python-and-python-d9236005.html on 17/09/2024.
• Click here or https://www.tutorialspoint.com/sdlc/index.htm.
• Computing – Teacher Manual (2024), Year One Book 2 for SHS, SHTS, STEM
curriculum – pages 4 – 95.
• Computing – Teacher Manual (2024), Year One Book 2 for SHS, SHTS, STEM
curriculum – pages 64 – 95.
• GeeksforGeeks. (n.d.). Linked List Data Structure. Retrieved from https://www.
geeksforgeeks.org/linked-list-data-structure/.
• GeeksforGeeks. (n.d.). Stack Data Structure. Retrieved from https://www.
geeksforgeeks.org/stack-data-structure/.
• https://www.javatpoint.com/software-development-life-cycle.
• Joshi, B. (n.d.). Stack, Queue and Trees. Retrieved from https://cse.sc.edu/~bjoshi/
csce101/attachments/Stack,%20Queue%20and%20Trees.pdf
• NaCCA (2023) Computing curriculum for Secondary Education (SHS 1-3) pages
44.
• NaCCA (2023) Computing curriculum for Secondary Education (SHS1-3) pages
42 – 45.
• NaCCA (2023) Computing curriculum for Secondary Education (SHS1-3) pages
48 – 49.
• Narasimha K. (2016) - Data Structures And Algorithmic Thinking With Python,
CareetMonk Publications, retrieved from https://www.pdfdrive.com/data-
structures-and-algorithms-in-python-e25119593.html on 22/08/2024, pages 14 -
19.
• OpenStax (2024) Introduction to Python Programming retrieved from https://
openstax.org/books/introduction-python-programming/pages/1-1-background
on 11/09/2024, page 7-37.
• Park A. (2022) - Python Programming for Beginners: The Ultimate Crash Course
to Learn Python in 7 Days with Step-by-Step Guidance and Hands-On Exercises.
97
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
98
SECTION 4 COMPUTATIONAL THINKING AND PROGRAMMING LOGIC
ACKNOWLEDGEMENTS
List of Contributors
Name Institution
99