0% found this document useful (0 votes)
46 views

Program Design

The document discusses program design and fundamental programming concepts. It introduces program design, pseudocode, flowcharts, variables, data types, constants, conditionals, arrays, loops, and functions. It emphasizes that program design is important before coding and that Python is a suitable language for program design due to its readability and similarity to pseudocode. The document also provides overviews of Python data types including strings, integers, floats, and lists.

Uploaded by

jonathan otshudi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Program Design

The document discusses program design and fundamental programming concepts. It introduces program design, pseudocode, flowcharts, variables, data types, constants, conditionals, arrays, loops, and functions. It emphasizes that program design is important before coding and that Python is a suitable language for program design due to its readability and similarity to pseudocode. The document also provides overviews of Python data types including strings, integers, floats, and lists.

Uploaded by

jonathan otshudi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Program Design

Mark demarcation

Unit 1: Introduction to program design

There are two parts to writing a program – designing the code and writing the
code. Once the logic of the design has been checked and corrected, the
design is ready to be translated into code. Much time can be wasted in trying
to find logical errors in a program that has been coded without a properly
checked design. Just as a builder should never build a house without a
properly drawn-up plan, one should never code a program without a proper
design.

In the Processing and Logic Concepts module, you learnt about program
flowcharts as a means of describing the flow of logic in a program.

Although a program flowchart is a useful tool for describing what a program


must do, it has definite shortcomings:

● Program flowcharts are time-consuming to construct.


● Flowcharts can become clumsy and unmanageable when describing
larger or more complicated programs.
● Flowcharts are often difficult to modify because they are drawings.
● Flowcharts are more difficult to read and follow, especially for larger
programs.
We learnt that pseudocode offers a program design alternative to flowcharts. It
is not code-specific, easily readable and can be translated into any high-level
computer programming language, but it cannot be tested programmatically.
We will use the Python programming language to test program logic in this
module.
You would use Python instead of pseudocode because it:

● Is a dynamic programming language that focuses on code readability.


● Has simple syntax that is easy to learn, so both new and experienced
programmers can start programming quickly.
● Has syntax that is very clear, so it is easy to understand the program's
code. Python is often referred to as "executable pseudo-code" due to its
syntax (Hilley, D. 2014). Python syntax mostly follows the conventions
used by programmers to outline their ideas without the formal verbosity
of code in most programming languages. In other words, the syntax of
Python is almost identical to the simplified "pseudo-code" used by many
programmers to prototype and describe their solution to other
programmers (Hilley, D. 2014). Thus, Python can be used to prototype
and test code which is to be implemented later in other programming
languages. Since you will study other programming languages (e.g.
Java/C#) later during your studies, Python will provide the necessary
foundation required when you start on the other programming
languages.

3. Programming Languages
There are many programming languages worldwide. Some of them, like C or
C++, are used for engineering applications or are used in game development,
while programs such as C#, Java and VB.NET are used in commercial
development and web development. Most of them use commands based on
the English language.

Programming languages are described as either low level or high level. The
closer the language is to machine code, the lower the level. Low-level
languages use ones and zeroes, and communicate directly with the
computer’s processor, whereas the high-level languages are more
English-based and need to be converted to zeroes and ones that can be
interpreted by the processor. The languages mentioned in the preceding
paragraph are all examples of high-level languages.

4. History of Python and Comparison to Other Languages


Python is a popular programming language. It was created by Guido van
Rossum and released in 1991. Python works on different platforms (Windows,
Mac, Linux, Raspberry Pi, etc.) and uses simple syntax like the English
language (pseudocode). The most recent major version of Python is Python 3.
Python version 3.8.2 will be used in this module to test your understanding of
program design concepts (Python.org, 2020).

Unlike C# and other languages, Python’s syntax is human-readable and


concise. As a beginner, this will allow you to pick up the basics quickly, with
less mental strain, and you can level up to advanced topics quicker pace. With
one glance at Python code, you can identify what the code is doing. In
contrast, most programming languages require more syntax (written code) to
accomplish similar tasks, and the syntax doesn’t mirror the human language.

Given the simplicity of Python’s syntax, you won’t need to memorise lots of
sections of code that are included in many different places.

6. CodeRunner
Programming examples provided in this module will be implemented in
CodeRunner. CodeRunner provides you with a platform to run a program; in
this case it will be a Python program. You will encounter CodeRunner when
you start the exercises in this module

To test your code, click the Check button to see if the code passes the tests
defined in the exercise/illustration.

1.2 Fundamental Programming Concepts

1. Introduction
The concepts discussed in this section are essential to anyone who wants to
become a programmer. These concepts are present in the majority of
computer programming languages and/or are a fundamental part of the
programming process. We will explore some of these concepts practically in
this module.

2. Algorithm
An algorithm is set of steps for carrying out a specific task. Algorithms are
used extensively in computer programming to arrive at a solution for a
problem. The process of creating an algorithm involves documenting all the
necessary steps needed to arrive at the solution and how to perform each
step. A real world example of an algorithm would be a recipe. The instructions
of a typical recipe (add ingredients, mix, stir etc.) are an algorithm

3. Variable

dir () can be used to get a list of built in functions in python

A variable is a container (placeholder), which represents a value in a program.


Variables can store different data types including numeric values, single
characters and text strings. The value of a variable can change all throughout
a program.

● A variable name should be short, simple, descriptive and meaningful


and the same name should be used throughout the program. The
variable names num, number, nums will all represent a different variable
name to the program.
● Some computer languages are case-sensitive and so the variable name
should be in the same case throughout the program. The variable Num
and num will therefore be treated as two different variables.
● Do not use an underscore to join two words. In fact, do not use any
symbols in variable names, for example num<five, greaterThan50%,
etc. will all be incorrect as the program will attempt to perform a
calculation when it finds a symbol.
● Variable names should begin with a small letter. When joining two
words, the first letter of the second word should be capitalised. For
example, totStud could be used to represent the total number of
students.

4. Data Type
A datatype is the classification of pieces of information in a program. The
amount of different data types varies between languages. Typically, there are
data types for integers (whole numbers), floating-point numbers (numbers with
a decimal part) and single characters. To distinguish between different data
types, a computer uses special internal codes.

5. Constant
A constant is the same as a variable with one major difference – the value of a
constant does not change, while the value of a variable can change
throughout a program.

6. Conditional
A conditional is set of code that will execute only if a certain condition is true.
Conditionals are used to test expressions and perform certain operations
accordingly. For example, you could test a number input by a user and if it is
too high, it prints the message, "The number entered is too high" and the
program exits. Thanks to conditionals, a program can work differently every
time it runs

7. Array
An array is a special type of variable used in many programming languages
that contains a list of related values. For example, a colour array would
contain a list of colours.

8. Loop
A loop is a segment of code that executes repeatedly based on a certain
condition. Loops are used to perform tasks a number of times. For example, if
you needed to print the numbers 1 to 10, you can use a loop for this task
instead of manually printing all the numbers.
9. Function
A function is a set of code used to carry out specific tasks. A function can take
parameters which will affect its output as well as return values. Functions
prevent unnecessary code because you can use them as much as needed
instead of retyping certain code over and over. For example, if you need to
multiply two numbers, instead of doing the calculation manually every time,
you can supply the data to a function through some parameters that will do it
for you.

1.3 Data Types

Python Data Types


Programming languages can process different types of data. Data types have different functions in a
program. One of the most important factors to take into consideration is that the performance of a
computer can be severely affected by choosing the wrong data type.
For example, a program might only need to use numbers between one and 20; it would therefore not
make sense to use string variables to store these numbers in, as one will need to convert these
strings back to numbers in order to perform calculations on them. This would create extra work for
the computer, which means that the performance could degrade in larger programs. Therefore, one
should rather define the variables as integers.
We will be working with the following built-in Python data types in this module:

Type Description Data Types

Text str

Numeric int, float

Sequence list

str – Strings – These are a sequence of Unicode characters, e.g. a word or a sentence that can be
manipulated. Strings are represented by the immutable (unchangeable) str data type.
int – Integers – These represent numbers in an unlimited range. This is only limited by a machine’s
memory. Integers are always whole numbers. Integers include negative and positive numbers, e.g.
8, 40, −3 etc.
float – Floating point numbers – Floating point numbers represent double precision numbers, e.g.
78.93.
list – List – A list is a collection that can hold data of any type, with a dynamic number of objects.
Lists use [] (square brackets) to define their elements.

Assigning Variable Data Types


In Python, variables are defined in a standard way by using the assignment character (=). This
changes the value of the variable. Naming conventions specify the way in which variables should be
named. This standard is used to make code more readable and thus easier to understand.
The rules include the start and continuation characters. Variable names may contain any upper or
lower case letters (A–Z, a–z), a number or the underscore character. They may not begin with a
number or contain spaces. Continuation characters are any characters except whitespace
characters, like tab and space.
Here are a few examples of valid variable names:
● c
● ref_number
● admin
● aVeryLongName

Here are a few examples of invalid variable names:


● True
● $name
● 12Graph

In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = ["apple", "banana", "cherry"] list

x = range(6) range
Casting Python Data Types
There may be times when you want to specify what data type a variable should be or change the
type of a specific variable.
This is known as casting. Casting in Python is done using predefined casting functions:

Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

Input

Input is data provided to the program by a user. In this module, all input is provided by myLMS and
will be illustrated in the block below. The result in the block below is the output of the program and
will be explained more in the output section of this quiz.

Note:
Program languages allow developers to add human-readable text to explain the code in a program.
These are known as comments. In Python, a single-line comment starts with a hash (#). All 'code'
after the # is seen as a comment and will not be executed as part of the program. Multi-line
comments in Python are surrounded by ''', for example:

'''
multi
line
comment
'''

Comments will be used to explain code in the code block.


Let's explore how we can get user input in Python.
The following code illustrates the syntax for obtaining input in Python using the predefined function.

For example:
Input Result

input input
input Provide input data: input
data data

Processing

Processing refers to the alteration or manipulation of the data and/or input data. Let's look at a
simple example of how we can manipulate variables with arithmetic logic operators, arrays and
functions. Arithmetic logic, as well as other operations, are explored further in Unit 2 – Logic
Operations and Control Statements. Arrays and functions are explored further in Unit 3 and Unit 4
respectively.

Output
Output refers to user feedback. It is usually the result of the input data after it has been processed.
Let's look at how to provide output in Python using the print() function

Unit 2: Logic Operators and Control


Statements
2.1 Operators in Python
Programs must often perform tasks that include calculations or making decisions based on the value
of one or more variables. A program could also be used to compare values and perform a certain
action based on the outcome. For these actions, operators are used. Operators are used to perform
operations on variables and values. Operators can manipulate individual items and return a result.
The data items are referred to as operands or arguments.
We will be working with the following Python operators in this module:
● Arithmetic operators
● Logic operators
● Comparison operators
● Membership operators
● Identity operators
2.1.1 Arithmetic Operators
Arithmetic operators perform various arithmetic calculations like addition, subtraction, multiplication,
division, % modulus, exponent, etc.

Operator Name Example

+ Add x+y

- Subtract x-y

* Multiply x*y

/ Divide x/y

% Modulus x%y
(Get the remainder of a division)

** Exponential x ** y

// Floor Division x // y
(Result of division in which the digits after the decimal point are removed)

Example: For arithmetic operators, we will take the simple example of addition where we will add two
digits: 4+5=9
x= 4
y= 5
print(x + y)
Similarly, you can use other arithmetic operators for multiplication(*), division (/), subtraction (-), etc.

2.1.2 Logic Operators


Logical operators were introduced in the Logic section of the Processing and Logic Concepts
course. For the purposes of this course, we will be using the three most common logical operators:
AND, OR and NOT. The use of logical operators results in only one of two values: TRUE or FALSE.

For logical operators, the following conditions are applied:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverses the result; returns False if the result is true not(x < 5 and x < 10)

Example: Here is an example where we get true or false based on the value of a and b.

a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))

2.1.3 Comparison Operators


These operators compare the values on either side of the operand and determine the relationship
between them. They are also referred to as relational operators. Various comparison operators are
==, != , <>, >,<=.

Operator Description Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Example: For comparison operators, we will compare the value of x to the value of y and print the
result as either true or false. Here in the example, the value of x = 4, which is smaller than y = 5, so
when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it
returns false.
x = 4
y = 5
print(('x > y
is',x>y))

2.1.4 Membership Operators


Membership operators are used to test if a sequence is presented in an object variable or list. There
are two membership operators that are used in Python (in, not in). It gives the result based on the
variable present in a specified sequence or string.

Operator Description Example

in Returns True if a sequence with the specified value is present in the x in y


object

not in Returns True if a sequence with the specified value is not present in the x not in y
object

Example: For example, here we check whether the value of x = 4 and the value of y = 8 are
available in the list or not by using in and not in operators.

x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 - x is available in the given
list")
else:
print("Line 1 - x is not available in the
given list")
if ( y not in list ):
print("Line 2 - y is not available in the
given list")
else:
print("Line 2 - y is available in the given
list")
2.2 Batch Processing vs Online Processing
Batch processing occurs when the program receives its input from a file and there is no interaction
with the user of the program. When dealing with file input, the read statement must be used when
entering data into the program.
Online processing occurs when the program is interactive and the user is prompted by the program
to enter input using the keyboard. When dealing with file input, the input statement must be used
when entering data into the program.

2.2.2 Selection Structure


Indentation refers to the spaces at the beginning of a code line. In other programming languages,
the indentation in code is for readability only; the indentation in Python is very important. Python
uses indentation to indicate a block of code. If the indentation is not done correctly, you will get a
syntax error in your code

2.2.3 Repetition
Repetition statements are used to execute a set of statements continuously if a specified condition
remains true. As soon as the condition changes to false, the set of statements is skipped and
execution continues from the line following the repetition statement.
● for
Executes a series of statements a fixed number of times.

● while
The while repetition statement (or while loop) repeatedly executes the statements in a loop
for as long as the loop continuation condition remains true. The loop continuation condition
follows the while keyword.

As soon as the condition becomes false, the loop exits. The while loop is used when a
programmer wants to execute a specific statement or set of statements repeatedly, but does
not know exactly how many times the statements will be executed.

For example, a sales manager may want to calculate the total sales achieved by all
salespersons during a month. For this, the manager may enter the sales amount of each
salesperson into a program and accumulate the sales amounts. Although the manager may
know the total number of salespersons to enter, what would happen if another manager
wanted to use the same program but had a different number of salespersons? The while
loop would allow both managers to use the same program, regardless of the number of
salespersons each needed to enter.
2.3 Control Structures
Program control structures are used to transfer control from one part of a program to another.
Sequence – Program performs tasks in sequence (in the order in which they were written).
Selection – Program performs a task depending on the validity of a given condition.
Repetition – Program performs a task repeatedly until a condition is satisfied.

2.3.1 Sequential Programs


In sequential programs, program statements are executed in the order in which they occur, line after
line, from top to bottom. Most programming languages use this method of programming, and the
sequence control structure is built into the program.
For example:

Input Result

8 Input number:
20 8
20
33

2.3.2 Selection Structure


Selection statements are also known as "decision making statements" or "branching statements".
The selection statements are used to select a part of the program to be executed based on a
condition.
Python provides the following selection statements:
● if statement
● if-else statement
● if-elif statement

The next section will explain more on the selection structures.


2.3.2.1 If Statement
An if statement is used for decision making in Python. It will run the body of code only when an if
statement is true. When you want to justify one condition while the other condition is not true, then
you use the "if statement".
Let us look at the pseudocode design example. The following if statement checks whether a variable
called "amount" is greater than 1000. If it is, a variable called "rate" is adjusted to the value of 0.2.
The program then calculates the interest with the statement: interest = amount * rate. If the amount
is less than or equal to 1000, the rate variable remains unchanged, and the interest is calculated
with the original value for rate:

if amount > 1000 then


rate = 0.2
endIf
interest = amount * rate

The beginning of the if statement is denoted by the keyword "if", followed by the condition to be
tested (in this case amount > 1000). The condition is followed by the mandatory keyword "then".

The statements following the "then" keyword must appear on separate lines (one line per statement).
In the above example, only one statement, rate = 0.2, is needed. The "endIf" keyword denotes the
end of the if statement. Also note that statements within the if…endIf block must be indented. This is
to improve the readability of the program.

The following shows the equivalent if statement as it would be shown in Python using CodeRunner.
The if statement is similar to the one shown in Section 2.3.2.1. It checks the value of the amount
variable, and if this exceeds 1000, the rate is set to 0.2. If the amount is less than or equal to 1000,
the rate is set to 0.1. This is indicated by the "else" keyword. Any statements that occur between the
"else" and "endIf" keywords are executed when the condition in the if statement is false.

The "endIf" keyword denotes the end of the if statement. Once again, the interest is calculated after
the execution of the rate variable has been set by the if statement.

The following shows the equivalent if statement as it would be shown in Python using CodeRunner.

2.3.2.3 if-elif Statement


The if…elif statement can be expanded to include many different values or cases to test for the
condition, by nesting one or more else if statements after the initial if statement.
In Python, when we want to test multiple conditions, we use the elif statement.
The following code snippet makes use of nested else if statements to check the mark of a student
and print a message depending on the value of the mark:
if mark >= 80 then
print "Distinction"
else if mark >= 70 then
print "Well done"
else if mark >= 60 then
print "Passed"
else
print "Failed"
endIf

Depending on the value of the mark, the else if block for which the condition is true will be executed.
For example, if the value of the mark is 77, the program first tests the condition mark >= 80.
Because the mark is less than 80, the program skips the condition and moves on to the next
condition (mark >= 70). Because the condition is now satisfied, the program executes the statement
inside this else if block and prints "Well done".

It is important to realise that the program will now exit the if statement completely and execute the
first line following the "endIf" keyword, if any. An if statement always executes the code after the first
condition in the set of else if statements is true and then exits the statement.

In the above example, although the next else if statement (else if mark >=60) also satisfies the
condition, it is not executed because the previous statement (else if mark >= 70) has already
satisfied the condition.

Also note that the final else in the if construct could have been replaced by else if mark >= 0 then. It
is not necessary for the final statement in a series of else if statements to be an else. The "else"
keyword is optional. The following shows the equivalent if statement as it would be shown in Python
using CodeRunner.
2.3.3 Repetition Structure
Repetition statements are used to execute a set of statements continuously if a specified condition
remains true. As soon as the condition changes to false, the set of statements is skipped, and
execution continues from the line following the repetition statement.

In Python, the iterative statements are also known as looping statements or repetitive statements.
The iterative statements are used to execute a part of the program repeatedly as long as a given
condition is true. Python provides the following iterative statements:
● while statement
● for statement

for

Executes a series of statements a fixed number of times.

while
The while repetition statement (or while loop) repeatedly executes the statements in a loop for as
long as the loop continuation condition remains true. The loop continuation condition follows the
"while" keyword.
As soon as the condition becomes false, the loop exits. The while loop is used when a programmer
wants to execute a specific statement or set of statements repeatedly, but does not know exactly
how many times the statements will be executed.
For example, suppose that a program requires that only numbers from one to ten may be entered by
a user. The following while statement can be used to check a value entered, print a message if the
value is invalid, and allow the user to re-enter the value:
input number

while number < 1 or number > 10 #check for an incorrect range

print "You must enter a number from 1 to 10" #prompt user for correct
number

input number # re-enter the number

endWhile


Note that a number is first entered by the user. The number is then checked using the while
condition. Note that the while loop checks for an incorrect value, outside of the range of
numbers from one to ten. The purpose of this is to prompt the user to re-enter the value of
the number, and allow him or her another opportunity to do so.

The while loop ensures that the user enters a number in the range from one to ten, and will
not continue past the endWhile statement until a valid number is input.
Let us look at the implementation of the pseudocode example in Python.

Here is the implementation of the above in CodeRunner

Just like any other programming language, Python contains its own syntax rules.

Indentation Rule

Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code. Python will give you an error if
you skip indentation.

White Spaces Rule

The number of spaces is up to you as a programmer, but it has to be at least one. You have to
use the same number of spaces in the same block of code, otherwise Python will give you an
error.

1. Python Syntax
Just like any other programming language, Python contains its own syntax
rules.
Indentation Rule

Indentation refers to the spaces at the beginning of a code line. Where in


other programming languages the indentation in code is for readability only,
the indentation in Python is very important. Python uses indentation to
indicate a block of code. Python will give you an error if you don't indent your
code.

White Spaces Rule

The number of spaces is up to you as a programmer, but there has to be at


least one. You have to use the same number of spaces in the same block of
code, otherwise Python will give you an error.

Example 1
A university wants a print-out of how many students failed the first year mathematics final
examination. Each record contains the student’s number, name, mathematics score and maximum
score possible. Each student must have a report printed with his or her number, name, percentage
and a remark stating whether a pass or fail is achieved (50% and above is a pass). Processing
continues until a student number of 0 is entered. Count how many students failed, as well as the
total number of students, and print these totals.

Pseudocode:
begin
totFail = 0
totStud = 0
input num
while num ≠ 0
input name, studScore, maxScore
perc = studScore / maxScore * 100
if perc >= 50 then
msg = “pass”
else
msg = “fail”
totFail = totFail + 1
endIf
totStud = totStud + 1
print num, name, perc, msg
input num
endWhile
print totFail, totStud
end

Note the following points from Example 1:

● The total number of students processed and the total number of failures are initialised to
zero.
● The first student’s number is input and the condition is tested before entering the loop. If this
number is 0, the loop will not execute. If the student number is not equal to 0, the rest of the
student’s data is input and processing begins.
● Remember that the student number is used as an exit condition for the program. Entering the
number separately from the rest of the student data is necessary to prevent the program
prompting the user to enter student data when the user wants to exit.
● For each record the percentage is calculated. If the percentage is greater than or equal to
50, “pass” is assigned to the message variable, otherwise “fail” is assigned, and the total
number of failures is incremented.
● The number of students in total is incremented.
● The record is printed and the next record is input, tested and processed.
● Processing stops when a student number of 0 is entered, at which point the total number of
failures and the total number of students processed are printed.

For example:

Input Result

32 32
David David
30 30
100 100
0 32 David 30.0
fail
0
1 1

Arrays

3.1 One-Dimensional Arrays


1D Arrays
An array is a data structure that consists of related data items (called elements) of the same data
type (any data type – strings, integers, etc.). An array may contain all character values or all number
values, but not a mixture of both.

An array usually has a fixed number of items or elements. Each element has a value. A program can
locate any element within the array. It takes no more time to locate element number 8 than it does to
locate element number 0. For this reason, an array is known as a random access data structure. The
figure below visually depicts an array with ten positions and its features.

Figure 2: One-Dimensional Array


Arrays can be used to ascertain the following types of values when dealing with numbers:
● The highest value in a group
● The lowest value in a group
● The total of all values
● The average value
● The highest average value
● The lowest average value

There are four collection data types in the Python programming language:
1. A list/array is a collection that is ordered and changeable. It allows duplicate members.
2. A tuple is a collection that is ordered and unchangeable. It allows duplicate members.
3. A set is a collection that is unordered and not indexed. It does not allow duplicate members.
4. A dictionary is a collection that is unordered, changeable and indexed. It does not
allowduplicate members.

Lists and arrays are used in Python to store dataBoth can be indexed and iterated. Arrays need to
be declared whereas lists do not need declaration because they are a part of Python's syntax. Only
lists and arrays will be covered in this module.
Example
# Initializing an array
# The following line sets the variable name cars, to an array with 3 string elements:

cars = ["Ford", "Volvo", "BMW"]

# "cars" being the array name containing 3 elements


# Ford, Volvo and BMW being the elements of the array
# Ford at index 0, Volvo being at index 1 and BMW being at index 2

# You can use the for loop to iterate through all the elements of an array.

for x in cars:
print(x)

# You can refer to an array element by referring to the index number:


# The following line sets the variable y to the value of the first element in the array

y = cars[0]
print(y)

# You can modify the value of the indexed array item:


# The following line updates the value of the first element in the array.

cars[0] = "Toyota"
print(cars[0])

# The following code snippet shows how the marks are loaded into the array
array = []
for m in range(5):
mark = input() # takes a string input
mark = int(mark) # converts the mark variable to an int
array.append(mark) # insert the mark variable into the array at the next available index
# append() method described in next section
print(array)

Array Methods
Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Adds the elements of a list (or any iterable) to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position


pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Example
# Refer to the method descriptions above for the following examples

cars = ["Ford", "Volvo", "BMW"]

# Example 1:
cars.append("Honda")
print(cars)

# Example 2:
cars.pop(1)
print(cars)

# Example 3:
cars.remove("Ford")
print(cars)

One-Dimensional Arrays Examples


Example 1
This example makes use of an array called marks to store the English marks obtained by a student
in each of the four terms of the year.
The task is to find the average percentage the student received for English for the year.

An array index tells us the position or address of a particular element in the array. The array index is
enclosed in square brackets. In this example, the indices are the numbers zero to three.
One of the most important things concerning arrays is to understand what exactly is being stored in
the array. This will help greatly when dealing with array questions in assessments. For example, the
array below holds the English marks obtained by a student in each term during the year.

For this specific array:


● marks[0] = 60
● marks[1] = 85
● marks[2] = 70
● marks[3] = 93

The following snippet shows how the marks are loaded into the array using pseudocode. Note the
use of the for loop once again when dealing with arrays and that the index (t) of the for loop is the
same variable as the index of the array.

for t from 1 to 4
input mark
marks[t] = mark
endFor

To calculate the average for the student, a for loop is used to accumulate the marks for the four
terms. This total is then divided by four.

begin
totTerm = 0
for t from 1 to 4 #Load the array
input mark
marks[t] = mark
totTerm = totTerm + marks[t] #Accumulate the marks
endFor
ave = totTerm / 4 #Calculate the average mark
print “Pupil average”, ave
end

Please note the following concerning the example:


● The mark total (totTerm) is initialised to zero before the for loop is entered.
● The for control statement (for t from 1 to 4) will execute four times. The variable t is a counter
and determines the number of times the statement(s) in the for loop will be executed; the
value of t in these statements increments for each iteration.
● In the processing loop, the marks for each term (which are contained in the array) are added
together. For example, the first time the loop executes the value of totTerm, it will equal 60.
The second time the loop executes the value of totTerm, it will equal 145 (60 + 85). The third
time the loop executes, totTerm will equal 215 (145 + 70). After the fourth execution of the
loop, the value of totTerm will equal 308 (215 + 93).
● The value of t in marks[t] depends on the current value of t in the for loop – that is, the first
time the for loop executes t = 1 and totTerm = totTerm + marks[1]. The variable t is
incremented until t = 4, when totTerm = totTerm + marks[4] is calculated. In this way all four
elements in the array are added.
● totTerm holds the total of all the term marks, which is used to determine the average mark.
● When processing is complete, the average is calculated by dividing the total of all four marks
by 4 (the number of terms). Dividing 308 by 4 gives an average of 77.
● The average mark obtained by the pupil is printed.

Python example

Example 2
In the following example, the same array is used as in the previous example to calculate the term
with the highest mark and the term with the lowest mark. The following variable names have been
used:
● Highest mark in a term: hiMark
● Lowest mark in a term: loMark
● Term with the highest mark: hiTerm
● Term with the lowest mark: loTerm
begin
hiMark = 0
loMark = 999
totTerm = 0

for t from 1 to 4
input mark
marks[t] = mark
if marks[t] > hiMark then
hiMark = marks[t]
hiTerm = t
endIf
if marks[t] < loMark then
loMark = marks[t]
loTerm = t
endIf
totTerm = totTerm + marks[t]
endFor
ave = totTerm / 4
print “Pupil average ”, ave
print “Best term”, hiT, “Marks =”, hiMark
print “Worst term”, loT, “Marks =”, loMark
end

The following points are noted from the answer above:

● The highest mark for a term is initialised to zero. This is because all elements in the array will
most likely be greater than zero.
● The lowest mark for a term is initialised to 999. This is because all elements in the array will
most likely be less than 999.
● The total mark variable (for all four terms – i.e. totTerm) is initialised to zero before entering
the for loop.
● The processing for loop will execute four times (once for each term and equivalent to the
number of elements in marks[4]).
● Each time the loop executes, the contents of the array is compared with the highest mark
(hiMark) and the lowest mark (loMark) found so far. The first time the loop executes, the
array element marks[1] contains the value of 60 (the value of marks[1]). As 60 is greater than
0, the value of hiMark is changed to 60. Because 60 is also less than 999, the value of
loMark is changed to 60. The term number, which is equal to the current index value of the
for loop, is stored in the variables hiTerm and loTerm.
● The second time the loop executes, the array element marks[2] equals 85. As 85 is greater
than 60, hiMark is assigned the value 85. Because 85 is greater than 60, loMark remains 60.
This process of comparing and replacing values where necessary continues until the loop
has executed four times.
● After the last repetition of the for loop, hiMark will contain the highest mark in the array and
loMark, the lowest mark.
● The average is calculated.
● The average is printed as well as the highest and lowest marks obtained for any term and
the term in which these marks were obtained.

Python Example

Two-Dimensional Arrays
A two-dimensional array is an array within an array. It is an array of arrays. In this type of array, the
position of a data element is referred by two indices instead of one.
Two-dimensional arrays are often used to represent tables of values in a row and column structure.
The first dimension of the array represents the row of the table and the second dimension represents
the table column, as depicted below.

Figure 3: Two-dimensional Array


Consider the example of recording temperatures four times a day, every day. Sometimes the
recording instrument may be faulty and we fail to record data.
● Day 1 – 23, 27, 11, 12
● Day 2 6, 10, 14, 5
● Day 3 25, 10, 17, 18
● Day 4 8, 9, 15, 12

Such data for four days, as shown above, can be presented as a two-dimensional array:
myArray =[[23,27,11,12],[6,10,14,5],[25,10,17,18],[8,9,15,12]]
To print out the entire two-dimensional array we can use a Python for loop, as shown below. We use
end of line keyword to print out the values in different rows.

Inserting Values in Two-Dimensional Arrays


We can insert new data elements in a specific position by using the insert() method and specifying
the index.
In the example below, a new data element is inserted at index position three.
Python example:

Updating Values in Two-Dimensional Arrays


We can update the entire inner array or some specific data elements of the inner array by
reassigning the values using the array index
Python example:

Deleting the Values in a Two-Dimensional Array


We can delete the entire inner array or some specific data elements of the inner array by reassigning
the values using the del() method with the array index. In case you need to remove specific data
elements in one of the inner arrays, use the update process described in Question 3.
Python example

Another Two-Dimensional Array Example


The following initialisation of an array has nine elements.
It has three rows and three columns that can be visualised as a table.

0 1 2

0 1 2 3

1 4 5 6

2 7 8 9
Output
Example 1
A car rental company keeps track of the kilometres driven by each of its cars in a week. The
following array stores the number of kilometres driven by each car in a day.

The kilometres are stored for each of the five cars, for each day of the week. For example, Car 2
drove 43 kilometres on Friday (day five of the week). The number of kilometres driven for each car is
entered at the end of each week.

The array can be defined as follows: kilometres[c, w] = carKilos

We want to find the combined average of all the cars’ kilometres driven in a week. The following
variable names are used:
● Total kilometres driven by all five cars for a whole week (seven days): totCarsKilos
● Total kilometres driven by each car for a whole week: totCar
● Average kilometres driven by a car in a day: average

begin
totCarsKilos = 0 # Total of all 35 input kilometre readings
for c from 1 to 5 # Load the array – first dimension, start with the
first car.
totCar = 0 # Total for kilometres driven by each car; reset to 0
for each car
for w from 1 to 7 # This is the second dimension, start with day
1
input kilos
kilometres[c, w] = kilos
totCars = totCar + kilometres[w, c]# Accumulating kilometres
for current car
endFor
totCarsKilos = totCarsKilos + totCar # Accumulate overall total
for all cars
endFor
average = totCarsKilos / (7 * 5) # or average = totCarsKilos / 35
print “Average kilometres driven by a car in a day: ”, average
end
Note the following points about the example:

The total amount of kilometres driven by all five cars in a week (totCarsKilos) is initialised before the
first for loop is entered. When both the for loops have finished executing, totCarsKilos will contain all
35 records of the kilometre readings in a week. We can then calculate the overall average distance
that the five cars drive in a day simply by dividing this total by 35. This is done on the first line of
code after the outer for loop.

A variable to store the total kilometres driven for a specific car (totCar) is initialised to 0 immediately
after the first for loop header (for c from 1 to 5). This is an important point to remember about arrays.
Any total that is initialised within a for loop applies to whatever item that for loop describes. In this
case, the for loop describes the car’s kilometres driven. Therefore, a total initialised program will
accumulate to the total for each car’s kilometres driven in a week, when the inner for loop has
finished executing.

The variable totCarsKilos is accumulated after the user has input the number of kilometres. Once all
seven kilometre readings have been input for the first car, the inner for loop ends, and the line
between the two endFor statements is executed. At this stage, totCar holds the total kilometres
driven in a week by the first car (c = 1). This total is added to the totCarsKilos variable to accumulate
the total kilometres of all the cars, one car at a time.

The outer for loop now executes for a second time and c = 2. The variable totCar accumulates the
kilometres driven in a week for the second car, and this total is added to the totCarsKilos once more.
This is repeated for all five cars before the overall average is calculated and printed.
Python example

Example 2
Using the same specifications as in the two-dimensional array (Example 1), determine the car(s)
with the highest average of kilometres driven in a day, as well as the average kilometres driven in a
day by all cars. Assume there may be more than one car with the highest average of kilometres
driven.

The following additional variable names have been used:

● Highest average kilometres driven by a car: hiAve


● One-dimensional array containing the average week’s kilometeres per car: ave[c]

begin
totCarsKilos = 0
hiAve = 0
for c from 1 to 5
totCar = 0
for w from 1 to 7
input kilos
kilometers[c, w] = kilos # Load kilometers input into array
totCar = totCar + kilometers[c, w]
endFor
ave[c] = totCar / 5 # Stores cars averages in a one-dimensional
array
if ave[c] > hiAve then # Checks for a higher average
hiAve = ave[c] # Stores the highest average so far
endIf
totCarsKilos = totCarsKilos + totCar
endFor
average = totCarsKilos / (7 * 5)
print “Average Kilometers driven by a car in a day”, average

for c from 1 to 5
if ave[c] = hiAve then

print “Highest average”, hiAve # Prints all cars averages


that equal hiAve
print “Car no:”, c
endIf
endFor
end

Note the following points about Example 2:

● The question calculates and prints the overall average of all 35 cars, exactly as in Example
1.
● The average for each car must be calculated before the highest average can be determined.
This is calculated by accumulating the kilometre readings for each car in the inner for loop
over a week and dividing by 7. These averages are stored in a one-dimensional array,
ave[c]. The index of the array is equal to the number of cars (c).
● The average for each car is then compared with the highest average, which is initialised to
zero at the start of the program. If the average is greater than the highest average, it
becomes the new highest average. For example, suppose that the average for the first car,
Car 1, is 93.3km. Since 93.3 is greater than zero the highest average becomes 93.3. The
next time the loop executes, the average is compared to 93.3, and hiAve is replaced if the
next average is greater than 93.3.

The final for loop at the end of the program runs through all five cars again and compares the
averages of each of these cars with the highest average, which was determined earlier in the
program. When a car’s average equals the highest average, this average is printed together with the
car’s number. Any subsequent cars also equal to the highest average are also printed, together with
their car numbers.
Functions
Functions (also called methods) are self-contained sections of code written by programmers in order
to perform a specific task. These functions are also known as user-defined functions. Although
functions are self-contained, they can interact with other functions in order to carry out their tasks.

The following are some of the characteristics of functions:


● They perform a specific task using self-contained units of code.
● They promote code maintainability. Changes made to a function should not affect the rest of
the program.
● Their code is hidden from other parts of the program
● They control which code other parts of the program may access, and to what extent they
may access it.
● They interact with the program or other functions through function calls.
● They are reusable. A function can be used (called) many times in the same program.

In Python, functions are used to utilise the code in more than one place in a program; they are
sometimes also called methods or procedures. Python provides you with many inbuilt functions like
print(), but it also gives you the freedom to create your own functions.
A function in Python is defined by the "def " statement followed by the function name and
parentheses ( () ).

The terms "parameter" and "argument" can be used for the same thing; the argument is a value that
is passed to the function when it iscalled. In other words, on the calling side it is an argument and on
the function side it is a parameter. In Python, arguments are declared in the function definition. While
calling the function, you can pass the values for that args. The return command in Python specifies
what value to give back to the caller of the function.
Keyword arguments

Keyword arguments in Python are used to pass additional information to a function. They are named
arguments, and they are passed after the positional arguments. For example,
my_function(arg1, arg2, keyword_arg=value).

Default arguments

Default arguments are arguments that are assigned a value by the function definition, and that
value is used if the argument is not passed in when the function is called. For example, the
following function has a default argument for the num_items argument:

def print_list(list, num_items=10):


for i in range(num_items):
print(listi)
Return statement

The return statement in Python is used to send a value back to the caller of the function. The
value can be any type of object, including numbers, strings, lists, and dictionaries.

The return statement is typically used at the end of a function, but it can be used anywhere
within the function. If the return statement is used without a value, the function will return None.

Here is an example of a function that uses the return statement:

def add_numbers(x, y):


return x + y

print(add_numbers(1, 2))

This code will print 3 because the add_numbers function returns the sum of its two arguments.

4.3 Recursive Functions


A function can call other functions. It is also possible for the function to call itself. These are known
as recursive functions.
An example of a recursive function is to find the factorial of an integer.
A factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is 1*2*3*4*5*6 = 720.

Example 1:
Write the code for a program that requests the user to input three numbers. A function then
calculates and prints the product of the numbers. A second function is then called from the main
program and calculates the average of the numbers. The average is returned to the main program
and printed.
program Numbers # Main program
begin
print "Enter 3 numbers"
input num1, num2, num3
determineProduct(num1,num2,num3) #Call to determineProduct function
result = determineAve(num1, num2, num3) #Call to determineAve
function
print "The average of the numbers is: ", result
end

function determineProduct(value1, value2, value3) #Code for


determineProduct function
begin
product = value1 * value2 * value3
print "The product of the numbers is: ", product
end

function determineAve(value1, value2, value3) # Code for determineAve


function
begin
average = (value1 + value2 + value3) / 3
return average
end

The following points can be noted regarding Example 1:


● The main program, Numbers, calls both functions one after the other. The first function
receives copies of all three numbers input by the user into the parameter variables (value1,
value2 and value3).
● After the function determineProduct() determines and prints the product of the numbers,
program control is automatically returned to Numbers, and continues to the next line, where
the determineAverage function is called.
● This function receives the three numbers as input parameters, calculates the average of the
numbers and returns the average to the variable result in the Numbers program without
printing it.
● The Numbers program receives the average in the result variable and prints it.
Example 2:
A program prompts for the user’s name and calls a function, which prints "Hello" followed by the
name. The function then prompts for the user’s age. The age is sent as an argument to a second
function, which returns a message to the first function depending on the age of the user. If the user is
older than 25, "You are too old" is returned to the calling function. If the user is between 17 and 25,
"You qualify" is returned. If the user is younger than 17, "You are too young" is returned. The main
program prints the user’s name followed by the return value. For example, if the user's name is Joe
and he is 18, the following message will be printed: “Hello Joe, you qualify”. The program then ends.
program Qualify
begin
print "Please enter your name"
input name
message = determineAge(name)
print name, message
end

function determineAge(name)
begin
print "Hello", name
print "Please enter your age"
input age
msg = checkAge(age) # calls checkAge before returning to program.
return msg # returns to program Qualify
end

function checkAge (value)


begin
if value > 25 then # if statement ensures only one message will
return "You are too old" # be returned
else if value > 16 then
return "You qualify"
else
return "You are too young"
endIf
end

The following points can be noted regarding Example 2:


● The main program calls the determineAge function with the user’s name as an argument.
● The determineAge function calls the checkAge function with the user’s age included as an
argument.
● Depending on the user’s age, an appropriate message is returned to the calling function of
checkAge, which is determineAge.
● Although there is more than one return statement in this function, the if…else statement
ensures that only one return will execute, depending on the age of the user.
● The message is stored in the msg variable. This value is then returned to the main program
(Qualify) and stored in the message variable.
● Finally, the name and message is printed by Qualify.

File Handling
What is a file?
A file is a collection of data that is stored on a storage device such as a hard disk, CD-ROM, DVD or
other storage medium. Files can be used for input, output or both. When a program reads from a file,
the relevant data from the file is input into the program and manipulated by the program. Data from
the program can also be written to a file for storage.

What is file handling?


File handling is an umbrella term for creating a file, opening a file, saving a data file, updating or
modifying data files, deleting a file, copying a file and closing a file.

What is a record?
Records are stored in files, which can be input into a program. A record can contain more than one
piece of data; for example, an employee record can consist of the employee number, name and
salary. The employee number, name and salary are known as data fields, or simply, fields. Each
employee record will consist of these three fields.

If information was entered for ten different employees and stored in a file, the file would then contain
ten records, each record consisting of three fields.

Opening a file
Text and binary can only be used in conjunction with another mode.
The key function for working with files in Python is the open() function.
The open() function takes two parameters: filename and mode.

There are four different modes for opening a file:


● "r" – Read – Default value. Opens a file for reading; returns an error if the file does not exist
● "a" – Append – Opens a file for appending; creates the file if it does not exist
● "w" – Write – Opens a file for writing; creates the file if it does not exist
● "x" – Create – Creates the specified file; returns an error if the file exists

In addition, you can specify if the file should be handled in binary or text mode:
● "t" – Text – Default value. Text mode
● "b" – Binary – Binary mode (e.g. images)

Reading a file

Note close method is: f.close()


To close the file automatically use the with statement:
The open() function returns a file object, which has a read() method for reading the content of the
file.

Writing to a file
To write to an existing file, you must add a parameter to the open() function:
● "a" – Append – will append to the end of the file; it will create the file if it does not exist
(working in an online environment, we will not be using this parameter due to file
permissions)
● "w" – Write – will overwrite any existing content; it will create the file if it does not exist
● "x" – Create – will create a file; it will return an error if the file exists
Example 1
Records are read from a file called "salary.txt". Each record contains the
following fields:
● number
● name
● gender
● gross pay

If a male employee earns over R5 000 a month, the record must be written to
the highTax.txt file, and the number of records written to this file must be
counted.
After processing and printing the records contained in salary.txt, all records in
the highTax.txt file must be printed.

Pseudocode Solution
#record
rec = enum, ename, gender, gpay
#endRecord

begin
totRecords = 0

open salary.fle for input # this file is used to read


data into the program
open highTax.fle for output # this file is going to be
written to
read rec from salary.fle # reads the whole record
while not EOF salary.fle # the input file
if rec.gender =”m” and rec.gpay > 5000 then
write rec to highTax.fle
totRecords = totRecords + 1
endIf

print rec
read rec from salary.fle
endWhile

print totRecords
close employee.fle
close highTax.fle
open highTax.fle for input

read rec from highTax.fle


while not EOF highTax.fle
print rec
read rec from highTax.fle
endWhile

close highTax.fle
end

Note the following points from the example:


● "rec" is the name given to a record in the file and contains the fields
enum, ename, gender and gpay.
● The total number of records written to the highTax.txt file is initialised to
zero.
● The program reads records from salary.txt and writes some of those
records to highTax.txt.
● An if statement is used to check for records where the gender is male
and the gross pay is over 5 000. These are written to the highTax.txt file.
The total number of records written to the highTax.txt file is incremented.
● Each employee record is printed by the program. The next record is
then read from the file.
● After all the records from the employee file have been processed and
printed, the total number of records in the highTax.txt file is printed. Both
files are then closed.
● The highTax.txt file is reopened and all records printed. Finally, the
highTax.txt file is closed.

Here is the example implemented in Python using CodeRunner


Example 2
Records containing employee details are read from the file employee.txt. Each
record contains the following fields: employee number, employee name,
hourly rate of pay and the number of hours worked.

Calculate the gross pay for each employee and write gross pay and the
associated employee number to a new file called "grossPay.txt". Accumulate
the gross pay in the grossPay.txt file and print this total.
● Within the firstloop, the gross pay for each employee is calculated. The
hours and rate fields are stored in a variable. In the next line, the value
of grossPay is calculated and assigned to the gPay variable. The record
is then written to the file grossPay.txt.
● The finalloop accumulates the gross pay for all employees from the
pay.txt file, and prints this total at the end of processing. The grossPay
file is then closed.
Example 3
Records containing employee details are read from the file employee.txt. Each
record in this file contains the following fields: employee number, employee
name, hourly rate of pay and the number of hours worked.

Calculate the gross pay for each employee and write this and the employee’s
number and name to a new file called "gross.txt".

When all the records in the employee.txt file have been processed, print all
the records in the gross.txt file.

● This example is similar to the previous one, but the gross.txt file now
includes extra fields.
● In the firstloop, the employee records are read into the program. The
gross pay for each employee is then calculated, as before, and together
with the employee number and name, is stored in each field of the
gpRec record.
● Print all records in the gross.txt file.

Example 4
Read in records from a file called "student.txt". Each record contains the
following fields:
● student number
● student name
● fees paid (y/n)

If the student’s fees have been paid, the record must be written to a file called
"paid.txt" and the total number of records written to this file must be counted
and printed. If the fees have not been paid, the record must be written to a file
called "arrears.txt". The principal wants a printout of all the students whose
accounts are in arrears.

● In the loop, if the student has paid his or her fees, the record is written
to the paid.txt file and the number of records written to this file is
incremented. If the student has not paid, the record is written to the
arrears.txt file.

Unit 6: Computer Science Algorithms


Bubble Sort algorithm
Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be
sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
This procedure is repeated until no swaps are required, indicating that the list is sorted. The steps for
implementing bubble sort are as follows:
1. In an unsorted array of five elements, start with the first two elements and sort them in
ascending order. (Compare the element to check which one is greater.)
2. Compare the second and third element to check which one is greater, and sort them in
ascending order.
3. Compare the third and fourth element to check which one is greater, and sort them in
ascending order.
4. Compare the fourth and fifth element to check which one is greater, and sort them in
ascending order.
5. Repeat steps 1 – 4 until no more swaps are required.

Write a Python function to perform bubble sort.

Merge Sort
Merge sort is a divide-and-conquer algorithm based on the idea of breaking down a list into several
sublists until each sublist consists of a single element, and merging those sublists in a manner that
results in a sorted list.
Merge sort is implemented with the following steps.
1. If there is only one element in the list, it is already sorted, return.
2. Divide the list recursively into two halves until it can no longer be divided.
3. Merge the smaller lists into a new list in the sorted order.

Write the Python function that implements merge sort.

So why choose one over the other?


Both have their pros and cons, but ultimately bubble sort quickly becomes less efficient when it
comes to sorting larger datasets (or ‘big data’), whereas merge sort becomes more efficient as
datasets grow.

Search Algorithms
Linear Search

1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[].
2. If x matches with an element, return the index.
3. If x doesn’t match with any of the elements, return −1.

Binary Search
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check
until the value is found or the interval is empty.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the middle index.
3. If x is greater than the middle element, then x can only lie in the right half of the subarray,
after the middle element. So we recur for the right half.
4. Otherwise if x is smaller, recur for the left half.

Write the Python function to implement a binary search.

The major difference between linear search and binary search is that binary search takes less time
to search for an element from the sorted list of elements. So it is inferred that the efficiency of the
binary search method is greater than the linear search.
Bubble sort example
This code works by repeatedly comparing adjacent elements in the array and swapping
them if they are in the wrong order. The outer loop iterates through the array from the
beginning to the end, and the inner loop compares each pair of adjacent elements. If the
current element is greater than the next element, they are swapped. This process
continues until the end of the array is reached, and the array is sorted.

The following is the output of the code:

[1, 2, 3, 5, 6, 7, 8, 9, 10]

As you can see, the array is sorted in ascending order.

Here is a brief explanation of the code:

● The bubble_sort() function takes an array as input and returns the sorted
array.
● The for loop in the bubble_sort() function iterates through the array from the
beginning to the end.
● The inner loop in the bubble_sort() function compares each pair of adjacent
elements in the array.
● If the current element is greater than the next element, they are swapped.
● The return statement in the bubble_sort() function returns the sorted array.

Linear Search Algorithim

This code works by starting at the beginning of the array and comparing each element
to the target value. If the element is equal to the target value, the index of the element is
returned. If the element is not equal to the target value, the next element is compared.
This process continues until the end of the array is reached. If the target value is not
found in the array, -1 is returned.

The following is the output of the code:

As you can see, the index of the element 5 in the array is returned.

Here is a brief explanation of the code:

● The linear_search() function takes an array and a target value as input and
returns the index of the target value in the array if it is found. If the target value is
not found, -1 is returned.
● The for loop in the linear_search() function iterates through the array from
the beginning to the end.
● The if statement in the linear_search() function compares the current
element in the array to the target value. If the elements are equal, the index of
the element is returned.
● The return statement in the linear_search() function returns -1 if the target
value is not found in the array.

I hope this helps! Let me know if you have any other questions.

Binary Search Algorithm


This code works by repeatedly dividing the search space in half and comparing the
target value to the middle element of the search space. If the target value is equal to the
middle element, the index of the middle element is returned. If the target value is less
than the middle element, the search space is reduced to the left half of the search
space. If the target value is greater than the middle element, the search space is
reduced to the right half of the search space. This process continues until the target
value is found or the search space is empty.

The following is the output of the code:

As you can see, the index of the element 5 in the array is returned.

Here is a brief explanation of the code:

● The binary_search() function takes an array and a target value as input and
returns the index of the target value in the array if it is found. If the target value is
not found, -1 is returned.
● The while loop in the binary_search() function iterates until the target value
is found or the search space is empty.
● The mid variable stores the index of the middle element of the search space.
● The if statement in the binary_search() function compares the target value
to the middle element of the search space. If the elements are equal, the index of
the middle element is returned.
● The elif and else statements in the binary_search() function update the
search space based on whether the target value is less than or greater than the
middle element.
● The return statement in the binary_search() function returns -1 if the target
value is not found in the array.

You might also like