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

Chapter 7 - Algotithms

The document provides an overview of algorithms, including their definitions, representations through descriptions and pseudocode, and the use of variables and constants. It discusses control structures such as simple sequences, selection structures (IF...THEN...ELSE), and loops (FOR...NEXT, Repeat...Until, and While...Do), along with examples in pseudocode and Visual Basic. Additionally, it touches on the importance of structure diagrams in illustrating program relationships and the top-down approach to programming.

Uploaded by

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

Chapter 7 - Algotithms

The document provides an overview of algorithms, including their definitions, representations through descriptions and pseudocode, and the use of variables and constants. It discusses control structures such as simple sequences, selection structures (IF...THEN...ELSE), and loops (FOR...NEXT, Repeat...Until, and While...Do), along with examples in pseudocode and Visual Basic. Additionally, it touches on the importance of structure diagrams in illustrating program relationships and the top-down approach to programming.

Uploaded by

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

COMPUTER ALGORITHMS AND

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:

Descriptions, Flowcharts,
Compiled by Madzingira
a. Descriptions:
- These are general statements that are
followed in order to complete a specific
task.
- They are not governed by any
programming language. An example is as
follows:

Enter temperature in o C
Store the value in box C
Calculate the equivalent temperature in
oF
Store the value in box F
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:

Enter centigrade temperature, C


If C = 0, then stop.
Compiled by Madzingira
Pseudo code uses keywords commonly found in high-level languages
and mathematical notation.
Variable:
Variable is memory location where a value can be stored.
Constants:
Just like variables, constants are "data holders". They can
be used to store data that is needed at runtime.
In contrast to variable, the content of a constant can't
change at runtime, it has a constant value. Before the
program can be executed (or compiled) the value for a
constant must be known.
Arithmetic
Use the arithmetic operators.
Assignment
Assignment is the process of writing a value into a
variable (a named memory location). For example, Count
← 1 can be read as „Count is assigned the value 1‟,
„Count is made equal to 1‟or „Count becomes 1. Values
are assigned to an item/variable using the ← operator.
Compiled by Madzingira
Initialization:
If an algorithm needs to read the value of a variable before it assigns
input data or a calculated value to the variable, the algorithm should
assign an appropriate initial value to the variable, known as
Initialization.
Input
We indicate input by words such as INPUT, READ or ENTER,
followed by the name of a variable to which we wish to assign the
input value.
Output:
We indicate output by words such as OUTPUT, WRITE or PRINT,
followed by a comma separatedlist of expressions.
Totaling
To keep a running total, we can use a variable such as Total or Sum
to hold the running total and assignment statements such as:
Total ← Total + Number
ADD Number to Total
Counting
It is sometimes necessary to count how many times something
happens.
To count up or increment
Compiled by 1, we can use statements such as:
by Madzingira
Structured statements
In the sequence structure the processing steps are carried out one after the
other. The
instructions are carried out in sequence, unless a selection or loop is
encountered.

ASSIGNMENT OPERATORS

Operator
Comparison
> Greater than
< Less than
>= Greater than
equal to
<= Less than equal
to
= Equals to
<> Compiled by Madzingira Not equal
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:

Enter first number, A


Enter second number, B
C=A+B
Print C
Stop
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
Compiled by Madzingira
II. SELECTION STRUCTURE:
- This allows one to choose the route
to follow in order to accomplish a
specific task.
- Selection is written using the
IF ....THEN...ELSE statement or
the CASE statement.

IF...THEN ...ELSE statement:


- A programming structure that allows
the user to choose one from at least
two routes of solving a problem.
Compiled by Madzingira
The IF THEN
statement

PSEUDOCODE
BEGIN
DECLARE grade As Integer

PRINT ("Enter your grade")


INPUT grade

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 Enter first Enter first
Number, A Number, A Number, A
Enter second Enter second Enter second
number, B number, B number, B
IF A>B THEN IF A > B THEN IF A>B THEN
Print A is Print A is Print A is bigger
bigger bigger IF A<B THEN
ELSE ENDIF Print B is bigger
IF A<B THEN IF A < B THEN IF A=B THEN
Print B is Print B is Print Numbers
bigger bigger are equal
ELSE ENDIF END
Print Numbers IF A = B THEN
are equal Print Numbers
ENDIF are equal
ENDIF ENDIF
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.

The algorithm below specifies what happens if the value


of Choice is 1, 2, 3 or 4.

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:

CASE OF OTHERWISE…
FLOWCHART
Pseudo code
BEGIN
DECLARE grade As Integer
PRINT ("Enter your grade")
INPUT grade
CASE grade OF
grade >= 80
PRINT ("Grade A")
grade >= 70
PRINT ("Grade B")
grade >= 60
PRINT ("grade C")
grade >= 50
PRINT ("grade D")
grade >= 40
PRINT ("grade E")
OTHERWISE
PRINT("Grade U, Repeat Exam")
END CASE Compiled by Madzingira
Program Code in Visual Basic Console Mode:

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,
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

The fore loop repeats statements a set number of


time. It uses a variable to count how many time it
goes
round the loop and stops when it reaches its limit

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
Compiled by Madzingira
Print Sum, count, Average
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
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.

PSEUDOCODE
VB CODE EXAMPLE
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
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
DOCODE 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
StopCompiled 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
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
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
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:

NetSalary = GrossSalary + Deductions + AidsLevy


The above formulae should have been correctly written
as
NetSalary = GrossSalary - Deductions - AidsLevy
- It is also an error generated by entering the wrong data
type during programCompiled execution,
by Madzingira for example, entering a
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
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
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
Compiled by Madzingira
2. DEBUGGING
TOOLS.
These are part of the
software which help
the user to identify
where the errors are.
The techniques
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
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
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
RY 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 Compiled by Madzingira
used if the algorithm had been shown using pseudocode.
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
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. Compiled by Madzingira

You might also like