COS 102 Note 1

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

COS 102: PROBLEM SOLVING

The Building Blocks

1
TABLE OF CONTENTS

1. INTRODUCTION TO PROBLEM SOLVING.................................................................................. 3


2. SOFTWARE DEVELOPMENT.................................................................................................... 7
3. USING FUNCTIONS FOR MODULAR PROGRAMMING............................................................. 13
4. STRUCTURED PROGRAMMING: SEQUENTIAL STRUCTURE.................................................... 15
4. STRUCTURED PROGRAMMING: SELECTION STRUCTURE...................................................... 16
6. STRUCTURED PROGRAMMING: REPETITION STRUCTURE..................................................... 21

2
Preamble
This is a set of notes for students of IT Applications and Foundations degree in
IT. These notes have been prepared as to cover some aspects of software
development that usually are omitted from the modules due to time pressures.
Rather than looking in the specifics of languages, web technologies and
development tools, we will look at the main skills that programmers must
develop to be able to use their knowledge effectively for tangible results.

Thus, we will look at the mental skills of analysis and organization of work to
turn the knowledge acquired in IT Apps to produce results.

1. INTRODUCTION TO PROBLEM SOLVING


An algorithm is a sequence of simple steps that can be followed to solve a
problem. These steps must be organized in a logical, and clear manner.

Algorithms are designed using three basic methods of control: sequence,


selection, and repetition.

1.1 Sequential control.


Sequential Control means that the steps of an algorithm are carried out in a
sequential manner where each step is executed exactly once.

Let’s look at the following problem: We need to obtain the temperature


expressed in Farenheit degrees and convert it to degrees Celcius. An algorithm to
solve this problem would be:

1. Read temperature in Farenheit


2. Apply conversion formula
3. Display result in degrees Celcius

In this example, the algorithm consists of three steps. Also, note that the
description of the algorithm is done using a so-called pseudocode. A pseudocode
is a mixture of English (or any other human language), symbols, and selected
features commonly used in programming languages. Here is the above algorithm
written in pseudocode:

READ degrees_Farenheit
degrees_Celcius =
(5/9)*(degrees_Farenheit-32) DISPLAY
degrees_Celcius
3
Another option for describing an algorithm is to use a graphical representation in
addition to, or in place of pseudocode. The most common graphical
representation of an algorithm is the flowchart.

1.2 Selection control.


In Selection Control only one of a number of alternative steps is executed. Let’s
see how this works in specific examples.

Example 1. This is an algorithm that decides whether a student should receive a


distinction.

READ grade
IF (grade >= 95)
THEN student receives a distinction

This is the simplest case of selection control. In fact, in essence it is a sequential


form but the second step is only taken when the condition contained in the
brackets is true, that is the last step (starting at THEN) is selected for execution
only when the condition is satisfied.

Example 2. Control access to a computer depending on whether the user has


supplied a username and password that are contained in the system database.

IF (username in database AND password


corresponds to user) THEN
Accept user
ELSE Deny user

In this case, there is also a decision to be made but a more complex one. If the
condition is true only the Accept user step is executed and if the condition is
false only the Deny user step is executed. That is, the condition helps us
make a selection which controls which of the two steps will be executed.

Now look more closely to the condition. Does it guarantee that the user is valid?
What if we had this condition instead, which looks pretty similar: IF (username
in database AND password in database)? What would happen is
somebody typed a valid username but the password of a different but also valid
user? Does this second condition satisfy our requirement that to access this
account one should be the right user and know the corresponding password?

4
Example 3. Decide on a student’s grade based on their coursework mark.

READ result
CASE (result >=90)
PRINT ‘A’
CASE (result >=80)
PRINT ‘B’
CASE (result >=70)
PRINT ‘C’
CASE (result >=60)
PRINT ‘D’
CASE (result <60)
PRINT ‘F’

5
In this case, there are five conditions which are checked, one after the other.

Question. What is the difference between examples 1, and 2, and 3?


Answer. There are three differences:

1. Example 1 provides no alternative action is the condition is not true.


2. Example 2 provides an alternative action when the conditions are false.
3. Example 3 provides multiple alternatives to select from.

1.3 Repetition.
In Repetition one or more steps are performed repeatedly.

Example 1. Compute the average of ten numbers:

total = 0
average = 0
FOR 1 to 10
Read number
total = total + number
END FOR
average = total / 10

Example 2. Read numbers and add them up until their total value reaches (or
exceeds) a set value represented by S.

WHILE (total < S) DO


Read number
total = total + number
END DO

Question. What is the difference between Examples 1, and 2?


Answer. The difference is that in Example 1 we know beforehand the exact
number of repetitions that will be carried out (they are 10), but in Example 2 we
do not know beforehand (it depends on the particular numbers that will be fed
to our program during its execution).

6
2. SOFTWARE DEVELOPMENT
A program is a sequence of instructions that a computer follows to solve a
problem. A program is written in a computer language. Most of the languages
have been created to fit particular classes of problems. Python is a versatile
programming language that has been designed to support a wide range of
applications, from web and desktop applications to data analysis and machine
learning. Unlike static languages, Python’s dynamic typing and high-level,
readable syntax allow for rapid application development, making it a popular
choice for developers around the world. The process of collecting requirements,
analyzing a problem and designing its solution as well as writing and maintaining
a computer program is called software development. It is important to note that
for most of this course, Python syntax will be used to write codes that are used
for examples and illustrations in the pages that follows.

2.1 The software engineering method for problem solving

The software engineering method is a way to approach problem solving using a


computer program and has the following five steps:

1. Specify the problem requirements. Describe the problem completely and


unambiguously.
2. Analyze the problem requirements. Identify (a) inputs, (b) the data to
work with, (c) outputs (i.e. desired results).
3. Design the algorithm to solve the problem. Write the step-by-step
procedures required to solve the problem. For large problems, don’t
attempt to solve every last detail of the problem at the beginning. Use a
top-down design that is, list the major steps first and break down the
problem into smaller and more manageable sub-problems. Once you know
the sub-problems you can attack each one individually. That might require
breaking down a sub-problem into even smaller sub-problems. This is
called algorithm refinement. This process of breaking down a problem
into its sub-problems is also called divide-and-conquer.
4. Implement the algorithm, that is convert the algorithm into a program.
5. Test and verify the completed program. Test the completed program to
verify that it works as desired. Do not rely on one test case. Run the
program several times using different sets of data. Try to imagine what
somebody who would like to violate your program would try to do.

Let’s see how this method works with a specific example:

1. Problem statement. You are the receiving clerk for an electronics parts
7
distributor that imports large quantities of wire and cable produced abroad and
sold in Nigeria. Most of the wire you receive is measured in meters; however,
your customers order wire by foot. Your supervisor wants you to compute the

8
length in feet of each roll of wire or cable that you stock. You have to write a
program to perform this conversion.

2. Analysis. You must convert from one system of measurement to another.


The problem statement says that you receive wire measured in meters; thus, the
problem input is wire length in meters. Your supervisor wants to know the
equivalent amount in feet, which is your problem output.

Next, you need to know the relationship between meters and feet. If you do not
know this already you open up a book that explains how you can convert length
measurements or you search on the Web. For example, if you look it up in a
table of conversions factors, you will find that one meter equals 39.37 inches. We
also know that there are 12 inches to a foot. These findings are summarized
below:

Inputs: Wire length in meter (wmeter)


Outputs: Wire length in feet (wfeet)
Additional program variable: Wire length in inches (winchs)
Relevant formulas or relations: 1 meter = 39.37 inches
1 foot = 12 inches

3. Design. Next, we have to formulate the algorithm to solve the problem.


We begin by listing the three major steps, or sub-problems, of the algorithm:

1. Read the wire length in meters


2. Convert the wire length from meters to feet
3. Display the wire length in feet

We then must decide whether any steps of the algorithm need further
refinement. Steps 1, and 3 need no further refinement. The refinement of step 2
shows how to perform the conversion:

2.1 Convert the wire length from meters to inches


2.2 Convert the wire length from inches to feet.

The complete algorithm with refinements is shown below:

1. Read the wire length in meters


2. Convert the wire length from meters to feet
2.1 Convert the wire length from meters to inches
2.2 Convert the wire length from inches to feet.
3. Display the wire length in feet

9
4. Implementation. The next step is to implement the algorithm
as a python function.

’’’
Converts wire length from meters to feet.
The user enters the wire length in meters.
’’’

def convert_meters_to_feet(length_in_meters):
length_in_feet = length_in_meters * 3.28084
return length_in_feet

# Convert the wire length from meters to feet

wire_length_in_meters = wmeter
wire_length_in_feet = convert_meters_to_feet(wmeter)
print(f"The length of the wire is {wire_length_in_feet} feet.")

For example:
Wire_length_in_meters = 10
Wire_length_in_feet = convert_meters_to_feet(10)
Print(f’The length of the wire is {wire_length_in_feet} feet.’)

10
A sample output of the program is shown below:

Length in feet is: 32.80833333333333

Let’s look at the different elements that we used to create this program.

Variables. Variables are quantities that can retain any value each time a
program runs:

var inchmt

Also wfeet, and inchft are variables. It is very important that variables have
meaningful names, because they make program easier to read, and understand.
If, for example, you name your variables m and f, it would not be straightforward
to remember what they represent.

Each language has special rules that restrict your selection of variable names. In
python, a variable name can be made up of small or capital letters, digits, and
underscore characters and the first character must always be a letter or the
underscore. Other characters, such as blanks, must not appear within a name.

A variable can be initialized (assigned to a value) during declaration for example

var inchmt = 39.37

or it can be assigned a value later on (after its declaration), such as

winchs = wmeter * inchmt;

Types. Variable inchmt holds a real value, and inchft holds an integer
value. Reals contain a fractional part, whereas integers are whole numbers.

11
Comments. Any line that starts with # is taken as a comment and thus ignored
by the computer. A comment can also be anything contained between ’’’ and
’’’ for example:

’’’
Converts wire length from meters to feet.
The user enters the wire length in meters.
’’’

and

# Helper variables

Assignment statements. We use assignment statements to give a value to a


variable. The assignment statement

winchs = wmeter * inchmt;

assigns the value of the expression wmeter * inchmt to variable winchs.

Operations. Addition and subtraction are denoted by the usual + and -


symbols. Multiplication is denoted by *, and division by /. The order of
evaluation follows the corresponding mathematical rules. Parentheses have
higher precedence in an expression. Multiplication and division follows. Addition,
and subtraction have the lowest precedence. Operations of the same precedence
are executed from left to right.

5. Testing and verification. Compare the program results with those that
you compute manually or by using a calculator. Keep in mind that programs
often have errors. We distinguish between two types of errors: Syntactic
(grammatical), and semantic (logical) errors.

Syntactic errors are caused by misspelled words, or the omission of a word or


part of it, such as

prnt("Length in feet is: ",convert(10));

12
Semantic errors indicate that there is an error in the logic of the program. Some
semantic errors might cause a failure (e.g. divide by zero), others might just
provide wrong results. For example, if we had used
winchs = wmeter + inchmt;

instead of the correct

winchs = wmeter * inchmt;

in the example above, then everything would seem to work as required but the
calculated result would be incorrect.

13
3. USING FUNCTIONS FOR MODULAR PROGRAMMING
In the previous section we discussed the divide-and-conquer approach to
program design. The main idea was to divide the overall task in smaller chunks
that we can handle more easily. Sometimes there are tasks that are being
repeated in several points in the program – we would want to write code only
once!

To do this in python, we use functions. Functions are relatively small program


units designed to perform a particular task. Functions have other characteristics
as well: When they terminate their execution, they return a single value; they
return values via their names; and finally, they are referenced by using their
name in an expression. For example, in the example of the previous section we
called functions convert in the following statement:

print("Length in feet is: ",convert_meters_to_feet(10));

There are mainly two different types of functions:

Library functions. Python provides many built-in or library functions. Any of


these functions can be used in any expression by giving its name followed by the
actual arguments to which the function is to apply.

For example, if we want to find the smaller of two variables, we can use
math.min function:

var num1, num2


smaller=math.min(num1,num2);

Function MIN gets two arguments: num1 and num2 and returns the minimum of
the arguments that is assigned to the variable minimum

Function subprograms. In many cases it is best to define additional functions.


A programmer-defined function can be used in the same way as any library
function. The general form of a programmer-defined function is

def myfunction(argument1,argument2,etc:
some statements

Example: Let’s write a function that calculates the area of a square given the
length of its side.

14
def square_area(side):

return side*side

Functions that will return a result must use the return statement. This
statement specifies the value that will be returned to the point where the
function was called.

15
4. STRUCTURED PROGRAMMING: SEQUENTIAL STRUCTURE
In section one we learnt that any algorithm (and thus any program) can be
structured using the three basic control structures: sequence, selection, and
repetition. In this and the following sections we will look at each of these
structures in turn, starting with the simplest one, the sequential structure.

The sequential structure is a simple way to refer to the execution of a sequence


of statements in the order in which they appear so that each statement is
executed exactly once. Consider the following sequence of statements:

# This is a simple Python program to demonstrate sequence structure

# Step 1: Print a welcome message


print("Step 1: Welcome to our program!")

# Step 2: Perform a calculation


result = (2 * 3) + (4 / 2)
print(f"Step 2: The result of the calculation is {result}")

# Step 3: Print a goodbye message


print("Step 3: Thank you for using our program. Goodbye!")

# The program ends here


print("End of program")

16
4. STRUCTURED PROGRAMMING: SELECTION STRUCTURE
The selection structure can take different forms: single selection, nested ifs and
multiple selection. We will discuss each case individually.

Single Selection

In the simplest selection structure, a sequence of statements (also called a block


of statements) is executed or bypassed depending on whether a given logical
expression is true or false. In Python the general form of the simple selection

is:

if (logical expression is true):


statement

It is also possible to specify an alternative statement sequence for execution


when the logical expression if false. The general form of the simple selection
with alternative action is:

if (logical expression is true):


statement
else:
some other statement

Example: The following code fragment reads the time from the system clock and
if it is earlier than 10am it displays the message “Good morning!”

from datetime import datetime

# Get the current time


current_time = datetime.now().time()

# Check if it's earlier than 10 AM


if current_time.hour < 10:
print("Good morning!")
else:
print("It's past 10 AM.")

Example: The following code fragment reads the time from the system clock and
if it is earlier than 10am it displays the message “Good morning!” and in every
other case it prints “Good day!”.

from datetime import datetime


17
# Get the current time
current_time = datetime.now().time()

# Check if it's earlier than 10 AM


if current_time.hour < 10:
print("Good morning!")
else:
print("Good day!")

Nested IF Statement

The statements in an IF construct may themselves contain other IF constructs.


In this case, the second IF construct is said to be nested within the first.

Example: Consider the following program that displays a student’s grade:

def display_result(mark):
if mark >= 90:
print("A")
elif mark >= 80:
print("B")
elif mark >= 70:
print("C")
elif mark >= 60:
print("D")
else:
print("F")

The order in which the choices are considered is very important!

Multiple Selection

The selection structure considered thus far, involved selecting one of two
alternatives. It is also possible to use the IF construct to design selection
structures that contain more than two alternatives. The switch construct is
used to select among multiple alternatives on the basis of a single expression
value. The general form of the case structure is

def switch(expression):
if expression == 'label1':
# code to be executed if expression = label1
pass
elif expression == 'label2':
# code to be executed if expression = label2

18
pass
else:
# code to be executed if expression is different from both label1 and label2
Pass

The expression is evaluated and compared to each selector, where each selector
is a list of possible values of the expression. Only one statement is executed. The
DEFAULT statement is optional and it is obeyed if none of the other CASE
statements produces a match.

Comparison between a nested IF and the case structure

We can start with an example: Consider the following price structure for concert
tickets:

Section Ticket price


0-99
100-199 25.00
200-299 25.00
300-399 20.00
400-499 15.00

Using a nested IF statement, one can have the following structure to assign the
desired value to price or displays an error message if the section is not listed in
the table:

if (section == 50):
price = 50.00;
elif ((section>= 100) AND (section <= 199)) OR (section>= 200) AND (section <= 299)):
print(“price = 25.00”)
elif ((section>= 300) AND (section <= 399)):
print(“price = 20.00”)
elif ((section>= 400) AND (section <= 499)):
print(“ price = 15.00”)
else:
print("Invalid section number”)

19
6. STRUCTURED PROGRAMMING: REPETITION STRUCTURE
The repetition of a block of statements a number of times is called a loop, and is
so important that Python support several different constructs to support this
feature.

The FOR construct

The FOR statement repeats a block of statements a predetermined number of


times, as specified by the initial value of an index variable that is incremented
until it reaches some final value. The general form of the for statement is

for (initialization; condition; increment)


{
code to be executed
}

In this case, the index variable is initialized at initialization and the code
is executed until condition is reached. At the end of each iteration the
variable is increased by increment.

Example 1: The following program segment will display the first 10 positive
integers:

for i in range(1, 11):


print(i)

The output will be: 1 2 3 4 5 6 7 8 9 10

Example 2: In the following example, the initial value for variable i is 1, and it
is incremented by 2, so the next values will be 3, 5, and so on. The following
segment would display the odd positive integers between 1 and 10.

for i in range(1, 11,2):


print(i)
Output will be: 1 3 5 7 9

20
In this example, when the i variable exceeds its final value (i.e. 10), there are
no more repetitions.

The following segment will compute the average of the first ten numbers:

# holds number of repetitions


limit = 10

# holds sum; initialized to 0


total = 0

# loop from 1 to limit (inclusive)


for index in range(1, limit + 1):
total = total + index # compute new total

# compute average
average = total / limit

print("The average is", average)

The WHILE construct

The while statement will execute a block of code while a condition is true.

while (condition)
{
code to be executed
}

Example 3. Let’s redo Example 1 using the while construct

i=0
while (i <= 5):
print(" ", i)
i +=1
The DO…WHILE construct

The do...while statement will execute a block of code once, and then it will
repeat the loop while a condition is true

do
{
code to be executed

21
}
while (condition)

22
Example 4. Let’s redo Example 1 using the do..while construct

i = 0
do
{
print(" ", i) i++
}
while (i <= 5)

Summary

Very often when you write code, you want the same block of code to run a
number of times. You can use looping statements in your code to do this. In
JavaScript we have the following looping statements:
● while - loops through a block of code while a condition is true
● do...while - loops through a block of code once, and then repeats the
loop while a condition is true
● for - run statements a specified number of times

23

You might also like