Chapter 7 - Algotithms
Chapter 7 - Algotithms
PROBLEM SOLVING
ALGORITHMS
Compiled by Madzingira
ALGORITHMS
- A set of instructions describing the steps
followed in performing a specific task, for
example, calculating change.
- They are a sequence of instructions for
solving a problem.
- Algorithms can be illustrated using the
following:
Enter temperature in o C
Store the value in box C
Calculate the equivalent temperature in o F
Store the value in box F
Print the value of box C and F
End the program.
Compiled by Madzingira
b. Pseudocodes:
- These are English-like statements, closer to programming language
that indicates steps followed in performing a specific task.
- They are means of expressing algorithms without worrying about
the syntax of the programming language.
- There are no strict rules on how pseudocode statements should be
written.
- Indentations are very important in writing pseudocodes since they
clearly indicate the extent of loops and conditional statements.
- They are however independent of any programming language.
- An example is as follows:
ASSIGNMENT OPERATORS
Operator Comparison
> Greater than
< Less than
>= Greater than equal to
<= Less than equal to
= Equals to
<> Not equal
() Group
AND And
OR Compiled by Madzingira Or
Data types
The following table shows the Visual Basic data types, their supporting common language
runtime types,
their nominal storage allocation, and their value ranges.
Basic Data Types
A variable can store one type of data. The most used data types are:
Compiled by Madzingira
CONTROL STRUCTURES/PROGRAMMING
CONSTRUCTS/BUILDING BLOCKS OF A
STRUCTURED PROGRAM
- A number of control structures are
used in designing Pseudocodes.
-These includes:
SIMPLE SEQUENCE,
SELECTION
ITERATION.
Compiled by Madzingira
i. SIMPLE SEQUENCE:
- This is whereby instructions are executed in the order
they appear in a program without jumping any one of
them up to the end of the program.
- Statements are executed one after another in the order
they are.
- It is simple and avoids confusion.
- Example:
PSEUDOCODE
BEGIN
DECLARE grade As Integer
IF grade > 50
THEN PRINT ("You have passed")
ELSE PRINT (“You have failed”)
END IF
END
Compiled by Madzingira
IF THEN, ELSE-IF statements VB code example
BEGIN
DECLARE grade As Integer
PRINT ("Enter a grade")
INPUT grade
IF grade > 80
THEN PRINT ("Grade A")
ELSE IF grade > 60
THEN PRINT ("Grade B")
ELSE IF grade > 50
THEN PRINT ("Grade C")
ELSE PRINT ("Grade U")
END IF
END IF
END IF
END
The IF statement is useful, but can get clumsy if you want to consider “multi-way selections
Compiled by Madzingira
Compiled by Madzingira
- The following Pseudocodes compares two numbers
entered through the keyboard and determines the bigger
one.
Enter first Number, A Enter first Number, A Enter first Number, A
Enter second number, Enter second number, Enter second
B B number, B
IF A>B THEN IF A > B THEN IF A>B THEN Print A
Print A is bigger Print A is bigger is bigger
ELSE ENDIF IF A<B THEN Print B
IF A<B THEN IF A < B THEN is bigger
Print B is bigger Print B is bigger IF A=B THEN Print
ELSE ENDIF Numbers are equal
Print Numbers are IF A = B THEN END
equal Print Numbers are
ENDIF equal
ENDIF ENDIF
END END
Compiled by Madzingira
CASE … OF … OTHERWISE … ENDCASE
For a CASE condition the value of the variable decides the path to be
taken. Several values are usually specified. OTHERWISE is the path
taken for all other values. The end of the statement is shown by
ENDCASE.
CASE Choice OF
1: Answer ← Num1 + Num2
2: Answer ← Num1 - Num2
3: Answer ← Num1 * Num2
4: Answer ← Num1 / Num2
OTHERWISE PRINT "Please enter a valid choice"
ENDCASE
Compiled by Madzingira
CASE Statement: This is an alternative to the IF...THEN...ELSE
statement and is shorter. For example:
Compiled by Madzingira
Cascaded/Nested If Statements
This is whereby if statements are found inside
other if statements (nested Ifs) as shown below:
Start
Enter “First Number”, A
Enter “Second Number”, B
Enter “Third Number”, C
If A>B Then
If B>C Then
Print “A is the biggest Number”
End If
End If
End.
Compiled by Madzingira
The algorithm below checks if a percentage mark is valid and a pass or a fail. This
makes use of two IF statements. The second IF statement is part of the ELSE path of
the first IF statement. This is called a nested IF.
Compiled by Madzingira
LOOPS (STRUCTURED
STATEMENTS FOR ITERATION
(REPETITION)
Compiled by Madzingira
iii. Repetition/Iteration/looping:
A control structure that repeatedly
executes part of a program or the
whole program until a certain
condition is satisfied.
Iteration is in the following forms:
FOR...NEXT LOOP,
REPEAT... UNTIL Loop,
WHILE...ENDWHILE Loop
Compiled by Madzingira
a. For...Next Loop:
A looping structure that repeatedly executes the loop
body for a specified number of times. This is to be used
when loop is to be repeated a known fixed number of
times. The counter is Automatically increased each time
the loop is performed.
The syntax of the For...Next loop is as follows:
FOR {variable} = {starting value} to {ending value} DO
Statement 1
Statement 2 loop body
................
NEXT {variable}
Compiled by Madzingira
A group of statements between the looping structures is called the loop body and is the
one that is repeatedly executed.
The For...Next loop is appropriate when the number of repetitions is known well in
advance, e.g. five times.
FOR count = 1 to 10
INPUT number
total = total + number
NEXT count
Compiled by Madzingira
BEGIN
DECLARE index As Integer
FOR index = 1 To 20
PRINT (index & “times 5 is" & index * 5”)
NEXT
Compiled by Madzingira
Other examples of FOR loop Sample VB Code of the Pseudocode:
BEGIN
DECLARE BiggestSoFar, NextNumber,
Counter As Integer
INPUT BiggestSoFar
FOR Counter 1 TO 5
INPUT NextNumber
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar NextNumber
ENDIF
END FOR
OUTPUT (“The biggest number
so far is” & BiggestSoFar)
END
Compiled by Madzingira
FLOWCHART FOR LOOP
Compiled by Madzingira
An example of a program that uses
the For...Next loop is as follows:
Sum, Average = 0
FOR I = 1 to 5 DO
Enter Number
Sum = Sum + number
NEXT I
Average = Sum/5
Display Sum, Average
End
Compiled by Madzingira
b. Repeat...Until Structure:
This is a looping structure that repeatedly executes the loop body
when the condition set is FALSE until it becomes TRUE. The
number of repetitions may not be known in advance and the loop
body is executed at least once. The syntax is as follows:
Repeat
Statement 1
Statement 2 loop body
................
Until {Condition}
For example
Sum, Average, Count = 0
Repeat
Enter Number (999 to end)
Sum = Sum + Number
Count = count + 1
Until Number = 999
Average = Sum / count
Print Sum, count, Average
End Compiled by Madzingira
In the above program:
- Count records the number of times
the loop body executes.
- 999 is used to stop further data entry
through the keyboard and thereby
ending the loop. Such a value that stops
further data entry through the keyboard
thereby terminating a loop is called a
Rogue value or sentinel.
Compiled by Madzingira
- The condition here is {Number = 999}. The loop
exits when the number 999 is entered. If 999 is
part of the number to be entered in this program,
then the user has to split it into two numbers, that
is 999 = 990 + 9, therefore can be entered
separately as 990 and 9.
- A flag is also used to control the loop. In this case
999 is also a flag.
NB. As for the Repeat...Until loop, the condition is
tested after the loop body has been run at least
once, even when the condition is true from start.
This is rather misleading.
Compiled by Madzingira
The repeat loop is similar to the while loop, but it tests the condition after the statements
have been executed once. This means that this test after loop goes round 1 or more times.
BEGIN
DECLARE name As String
REPEAT
INPUT name
PRINT (“Your name is:” name)
UNTIL name = "x"
END
Keeps inputting name and keeps printing name until user enters “X”
Compiled by Madzingira
Compiled by Madzingira
c. While ... Do LOOP
A looping structure in which the loop
body is repeatedly executed when the
condition set is TRUE until it becomes
FALSE. It is used when the number of
repetitions is not known in advance. The
condition set is tested first before
execution of the loop body. Therefore
the loop body may not be executed at all
if the condition set is FALSE from start.
Compiled by Madzingira
The wile look is known as a test before loop.
The condition is tested before entering
the loop, but tested each time it goes round
the loop. The number of times the statements
within the loop are executed
varies. The test before loop goes round 0 or
more times.
This method is useful when processing files
and using “read ahead” data
Compiled by Madzingira
PSEUDOCODE VB Code example
BEGIN
DECLARE name As String
INPUT name
WHILE name <> "x"
PRINT (“Your name is: “name)
INPUT name
END WHILE
END
Compiled by Madzingira
Compiled by Madzingira
The syntax of the WHILE…ENDWHILE structure is as
follows:
WHILE {condition}
Statement 1
Statement 2 loop body
................
ENDWHILE
An example of the program is as follows:
Sum, Count, Average = 0
WHILE Count < 6 DO
Enter Number
Sum = Sum + number
Count = count + 1
ENDWHILE
Average = Sum/count
Display sum, count, average
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Start
Enter number, A
Enter number, B
Sum = A + B
Display Sum
Stop Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Flowchart (a) above indicates
modules named Accept Numbers,
Add numbers Multiply Numbers
and Display Results. Flowcharts
for individual modules can then
be designed as given in diagram
(b) above, only the first module is
indicated. Can you do the rest?
Compiled by Madzingira
d. Structure Diagrams/Structure
Charts:
These are diagrams that show
relationships between different modules,
thereby giving the structure of a
program. They also illustrate the top-
down approach to programming. It is
useful as a documentation of a complex
program once it is completed. It
resembles a family tree as given below.
Compiled by Madzingira
Compiled by Madzingira
- The structure diagram above indicates five
sub-programs of the program Process
Numbers, namely Initialise, Accept Numbers,
Process Numbers, Display Results and Exit.
- The module Process Numbers has its own
sub-programs, which are Add Numbers and
Multiply Numbers.
- Modules are appropriate for very large
programs.
Compiled by Madzingira
- If the module is repeatedly executed (loop),
then an asterisk (*) must be placed at the top
right corner of the module (inside).
- All the boxes at the same level indicate
selection.
- Boxes below others indicate sequence.
- The program can be written as a continuous
single program as indicated on the right side
of the diagram
Compiled by Madzingira
PROGRAMMING ERRORS
Programming errors are grouped into:
i. Syntax error:
- this is an error of violating the grammatical
rules governing sentence construction in a
certain programming language, for example,
misspelled reserved words or leaving out a
semi-colon at the end of each line in Pascal.
- Syntax errors are detected by the computer.
A program cannot run with syntax errors.
Compiled by Madzingira
ii. Logic error (Semantic error):
- refers to an error in the sequencing of instructions, modules and
specifying wrong formulae that will produce undesirable results.
- For example, specifying a jump instruction to the wrong procedure
or instructing the computer to display result before any processing
has been done.
- Logic errors cannot be detected by the computer.
- The user just finds wrong and unintended results of a process.
- For example:
Compiled by Madzingira
iii. Runtime (execution) error:
-These are errors that occur during
program execution and can be generated
when the computer tries to read past an
end of file marker or by dividing a
number by zero.
-Arithmetic error: An the arithmetic
error, occurs in an instruction which
performs inappropriate arithmetic, e.g
Dividing a number by zero is an
arithmetic error.
Compiled by Madzingira
Type Mismatch error
A type Mismatch error occurs in a
program when a variable has been
declared as one data type, but it is later
assigned a value that is of an
incompatible data type. The following
code will produce a „Type Mismatch‟
error because “Edith” is not an integer:
DIM MyCounter AS Integer
MyCounter = “Edith”
Compiled by Madzingira
INTERPRETING AND TESTING PROGRAMS
DEBUGGING:
- The process of finding and correcting errors in a
program.
- Bugs are errors in a program.
- A debugger is a program used in aiding the
finding and removal of errors in a program.
- A number of tolls are employed to identify and
correct errors and these are:
Compiled by Madzingira
1. TRANSLATOR DIAGNOSTICS.
Each of the commands that are in the original
program is looked at separately by the computer
translator to execute it. Each command will have a
special word which says what sort of command it
is. The translator looks at the special word in the
command and then goes to its dictionary to look it
up. The dictionary tells the translator program
what the rules are for that particular special word.
If the word has been typed in wrongly, the
translator will not be able to find it in the
dictionary and will know that something is wrong.
Compiled by Madzingira
If the word is there, but the rules governing
how it should be used have not been followed
properly, the translator will know that there
is something wrong. Either way, the
translator program knows that a mistake has
been made, it knows where the mistake is
and, often, it also knows what mistake has
been made. A message detailing all this can
be sent to the programmer to give hints as to
what to do. These messages are called
translator diagnostics.
Compiled by Madzingira
2. DEBUGGING TOOLS.
These are part of the
software which help the
user to identify where the
errors are. The techniques
available include:
Compiled by Madzingira
a) Cross-referencing.
This software checks the program that has been
written and finds places where particular variables
have been used. This lets the programmer check to
make sure that the same variable has not been used
twice for different things.
b) Traces.
A trace is where the program is run and the values
of all the relevant variables are printed out, as are
the individual instructions, as each instruction is
executed. In this way, the values can be checked to
see where they suddenly change or take on an
unexpected value.
Compiled by Madzingira
c) Variable dumps (check/watch).
At specified parts of the program, the values
of all the variables are displayed to enable the
user to compare them with the expected
results.
3. DESK CHECKING (DRY RUN.)
The user „works through‟ the program
instructions manually, keeping track of the values
of the variables. Most computer programs require
a very large number of instructions to be carried
out, so it is usual to only dry run small segments
of code that the programmer suspects of
Compiled by Madzingira
- Using trace t- the process of manually
testing the logic of a program on paper
before coding on the computer, usually using
trace tables.
- Dry running is done to determine the logic
of a program (to check if it gives intended
results.)
one is able to trace through the program
manually, writing values of variables at each
stage until the end of the program or
module.
Compiled by Madzingira
DRY RUNNING AN ALGORITHM.)
A TRACE TABLE can be used to record the results from each step in an algorithm; it
is used to record the value of an item (variable) each time that it changes. This manual
exercise is called a DRY RUN. A trace table is set up with a column for each variable
and a column for any output. For example:
Compiled by Madzingira
Test data is then used to dry run the flowchart and record the results on the trace
table.
Test data: 9, 7, 3, 12, 6, 4, 15, 2, 8, 5
Compiled by Madzingira
Test data is then used to dry run the flowchart and record the results on the trace
table.
Test data: 9, 7, 3, 12, 6, 4, 15, 2, 8, 5
RESULTS OR OUTPUT
It can be seen from the output that the algorithm selects the largest and the smallest
numbers from a list of 10 positive numbers. The same trace table could have been
used if the algorithm had been shown using pseudocode.
Compiled by Madzingira
DATA TESTING
After a program has been
coded, it must be tested with
different data types to
determine if intended results
are produced. The types of
test data that can be used
include:Compiled by Madzingira
i. Extreme Data:
Refers to the minimum and the maximum
values in a given range. For example, a
computer program requires the user to enter
any number from (between) 1 to 20. 1 and 20
are extreme data and the computer must
accept these. Thus extreme data is accepted
by the computer.
ii. Standard (normal) Data:
This refers to data that lies within (in-between) a
given range. In our example above, the numbers
from 2 to 19 are standard data and are accepted by
Compiled by Madzingira
iii. Abnormal Data:
This refers to data outside a given range. As to
our example above, the number 0, -1, -50 and
all number from 21 and above are abnormal
data.
iv. Valid data: refers to data of the correct
data type. Invalid data is data of the wrong
data type. Thus if the user enter the value
“Terrence” instead of a number, this is
referred to as a wrong (invalid) data type.
Only numbers are needed, not text.
Compiled by Madzingira
PROGRAM TESTING
Can be done using the following
testing methods:
Unit testing, Integration Testing,
User acceptance testing, black box
testing, white box testing,
bottom-up testing, top-down
testing, etc.
NB: Research on the above program testing methods and
write notes. Compiled by Madzingira