Problem-Solving and Design

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 136

Candidates should be able to:

• show understanding that every computer system is made up of sub-


systems, which in turn are made up of further sub-systems
• use top-down design, structure diagrams, flowcharts, pseudocode,
library routines and sub-routines
• work out the purpose of a given algorithm
• explain standard methods of solution
• suggest and apply suitable test data
• understand the need for validation and verification checks to be made
on input data (validation could include range checks, length checks,
type checks and check digits)
Candidates should be able to:
• use trace tables to find the value of variables at each step in an
algorithm
• identify errors in given algorithms and suggest ways of removing
these errors
• produce an algorithm for a given problem (either in the form of
pseudocode or flowchart)
• comment on the effectiveness of a given solution
What is a computer system?
A COMPUTER SYSTEM is made up of software, data, hardware,
communications and people; each computer system can be divided up
into a set of sub-systems.

Each subsystem can be further divided into sub-systems and so on until


each sub-system just performs a single action.
Tools and techniques
A computer system is often divided up into sub-systems.

This division can be shown using top-down design to produce structure


diagrams that demonstrate the modular construction of the system.

Each sub-system can be developed by a programmer as sub-routine or


an existing library routine may be already available for use.
The program development life cycle
The program development life cycle is divided into five stages: analysis, design,
coding, testing and maintenance.
stages listed below:

• analysis

• design

• coding

• testing
The program development life cycle
Decomposition breaks down a complex problem into smaller parts, which can then
be subdivided into even smaller parts, that can be solved easily. Any daily task can
be divided into its constituent parts.

Design
The program specification from the analysis stage is used to show to how the
program should be developed. When the design stage is complete, the programmer
should know what is to be done, i.e. all the tasks that need to be completed, how
each task is to be performed and how the tasks work together. This can be formally
documented using structure charts, flowcharts and pseudocode.
The program development life cycle
Coding and iterative testing
The program or set of programs is developed. Each module of the program is
written using a suitable programming language and then tested to see if it works.
Iterative testing means that modular tests are conducted, code amended, and tests
repeated until the module performs as required.

Testing
The completed program or set of programs is run many times with different sets of
test data. This ensures that all the tasks completed work together as specified in the
program design.
Top-down design
TOP-DOWN DESIGN is the breaking down of a computer system into a
set of subsystems, then breaking each sub-system down into a set of
smaller sub-systems, until each sub-system just performs a single
action.

• This is an effective way of designing a computer system to provide a


solution to a problem, since each part of the problem is broken down
into smaller more manageable problems.
• The process of breaking down into smaller sub-systems is called
‘stepwise refinement’.
Top-down design
Advantages of top down
- When working on a large system many programmers can be assigned
individual modules to work on therefore speeding up the process of
developing and testing the system.
- Individual modules can be tested independently making it easy to
identify and correct errors.
- Easy to expand the system as new modules can be easily added to the
existing system.
- Separate modules can be kept independently and re-used when
needed.
- Allows specialisation as programmers can continue working on
modules related to their area of specialisation.
Top-down design- Alarm app for a smart phone
• Consider the alarm app computer system for a smart phone. This
could be divided into three sub-systems,
• setting the alarm,
• checking for the alarm time,
• sounding the alarm.
• These sub-systems could then be further sub-divided; the structure
diagram makes the process clearer.
Top-down design- Alarm app for a smart phone
Flow chart
Pseudo code
Algorithms
An algorithm is a sequence of steps which when followed mechanically
will lead to a solution of a problem.
Flowcharts
A FLOWCHART shows diagrammatically the steps required for a task (sub-
system) and the order that they are to be performed. These steps
together with the order are called an ALGORITHM.

Pseudocode
PSEUDOCODE is a simple method of showing an algorithm, using English-
like words and mathematical operators that are set out to look like a
program.
Algorithms
Library routines
A LIBRARY ROUTINE is a set of programming instructions for a given
task that is already available for use. It is pre-tested and usually
performs a task that is frequently required. For example, the task ‘get
time’ in the checking-for-the-alarm time algorithm would probably be
readily available as a library routine.
Sub-routines
A SUB-ROUTINE is a set of programming instructions for a given task that
forms a subsystem, not the whole system. Sub-routines written in high-
level programming languages are called ‘procedures’ or ‘functions’
depending on how they are used.
Algorithms
A TRACE TABLE is 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:

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
Structure of an algorithm
An algorithm must always consist of 3 parts
1. Input
The algorithm must take in some form of input for it to work.
Whenever you design an algorithm ensure you have made a provision
for some input to be entered.
2. Process
An algorithm must perform some of calculations, which could be
addition, subtraction, comparisons.
3. Output
An algorithm must produce some form of output, which can be printed
or displayed.
Flow chart symbols
Symbol Description Example

Terminator, denotes the start or end of a flowchart


Start
Input / Output used to denote data input or output. Input/ output will
have 1 entry point and 1 exit
Input Num1, Num2

Decision used to represent a decision in an flowchart. It has one input and


two outputs which could True or False / Yes or No
Num1> Num2?

Process used to denote processing which could be making calculations or


assigning a value to a variable.
Num1 = Num1 + 5

Off page connector, used to link part of a flow chart to the other part on
another page, if it fails to fit on one page
Flow charts
Activity 9.4
• Have a look at the flowchart and pseudocode on the next slide. What
is the purpose of the algorithm that they both represent?

• What would be output if the numbers 7 and 18 were input?


Flow charts
Flow charts
Activity
• Draw a flow chart to input 3 numbers, add them up and output the
total

• Draw a flow chart to input 2 numbers, Subtract number1 from


Number2 and output the Answer.
Class exercise

0478_w18_qp_22-pages-10-11
Flow charts
(a) Complete the trace tables for each set of input data.
Input data: 6, 2.5, 2

Height Depth Chlorine OK OUTPUT

6 2.5 2 true Pool OK to use


Flow charts
(b) Complete the trace tables for each set of input data.
Input data: 4, 3, 1.5

Height Depth Chlorine OK OUTPUT

4 3 1.5 True Water too deep


False
Flow charts
(c) Complete the trace tables for each set of input data.
Input data: 6, 3.5, 4

Height Depth Chlorine OK OUTPUT


Homework
Question 1
Six terms associated with programming and six descriptions are listed
on the next slide.

Draw a line to link each term with its most appropriate description.
Homework
Term Description

Top-down design Pre-written code to include in your own program to carry out a common
task.

Structure diagram Shows the steps representing an algorithm using various shapes of boxes.

Flowchart Shows the hierarchy of the different components which make up a system.

Pseudocode Shows the values of variables as you manually test your program.

Library routine Breaks down a system into successively smaller pieces.

Trace table Describes a program using a simplified high-level notation.


Homework
• The flowchart on the next slide performs a mathematical process on a
number input called TestNum
• DIV is used to represent integer division e.g. 7 DIV 3 = 2
Homework
Homework
(a) Complete the trace table for the input data: 7(2) Flag TestNum Num OUTPUT

(b) Complete the trace table for the input data: 6 (2) Flag TestNum Num OUTPUT

(c) State the purpose of the algorithm in the flowchart.


...................................................................................................................................................
...............................................................................................................................................[1]
Test data
Test data
When testing a program 3 types of test data should be used:
1. Normal data – Normal data is data within the range which should be
accepted by the program. For example if marks range from 0 to
100, normal data would be marks like 3, 87, 45.
2. Extreme data - Extreme data is data on the boundary of acceptance
and should be accepted by the program. For example if marks for a
test range from 0 to 100 then abnormal data will be 0 and 100.
3. Abnormal data – Abnormal data is data outside the given range
which also include illegal keystrokes. Form example if marks range
from 0 to 100, abnormal data would me marks like -4, -40, 101, t,
etc
Stages in producing an algorithm
1 Make sure that the problem is clearly specified.
2 Break the problem down into sub-problems; if it is
complex, you may want to consider writing an
algorithm for each sub-problem. Most problems, even
the simplest ones can be divided into:
• set up (Initialisation of variables)
• input
• processing
• output of results.
13 March
practice Practice activities
activities
Stages in producing an algorithm
• 3 Decide on how any data is to be obtained
and stored, what is going to happen to the
• data and how any results are going to be
displayed.
• 4 Decide on how you are going to construct
your algorithm, using a flowchart or
pseudocode.
Stages in producing an algorithm
• 5 Construct your algorithm, making sure that it
can be easily read and understood by
someone else. This involves setting it out
clearly and using meaningful names for any
data stores.
• 6 Use several sets of test data (normal,
abnormal and boundary) and trace tables to
find any errors.
Stages in producing an algorithm
• 7 If any errors are found, repeat the process
until you think that your algorithm works
perfectly.
Example – Algorithm to calculate area
of a rectangle
Length  0
Width 0
Area 0
INPUT Length
INPUT Width
Area Length * Width
OUTPUT Area
Tasks

1. Write an Algorithm to calculate the area of a


triangle.
2. Write an Algorithm to calculate the area of a
circle. (remember pie = 22/7 = 3.1429
Programming constructs

There are 3 programming constructs namely:

1. Sequence
2. Selection
3. Iteration
Sequence
1. In sequence a block of statements is
executed in the order they are given and
each statement is executed once.
Structure
Start
<Statement 1>
<Statement 2>
<Statement 3>
End
Sequence
1. Example

Start
Total  0
Number1, Number 2 , Number 3,  0
INPUT Number1
INPUT Number 2
INPUT Number 3
Total  Number1 + Number 2 + Number3
OUTPUT Total
End
Sequence
1. An algorithm to accept 4 numbers and
calculate the total
rithm

Start
algo

Total 0
his
ent t

Number1, Number2 , Number3, Number4  0


lem

INPUT Number1
basi m to imp

INPUT Number 2
INPUT Number 3
in vi a progra
c

Total  Number1 + Number2 + Number3 + Number4


sual

OUTPUT Total
e
Writ

End
Task
1. Write an algorithm to accept 4 numbers and calculate the
average.

2. Write an program to accept 4 numbers and calculate the


average.
Looking back

1. Write an algorithm to accept 2 numbers add them and


output the answer.
2. Write an algorithm to accept 4 numbers and calculate the
average.
3. Write an algorithm to input a mark and output Pass if the
mark is greater than 49, or output Fail if the mark is below
50.
4. Write an algorithm which will input 2 numbers and output the
largest.
Looking back

1. Write program to accept 2 numbers add them and output the


answer.
2. Write program to accept 4 numbers and calculate the
average.
3. Write program to input a mark and output Pass if the mark is
greater than 49, or output Fail if the mark is below 50.
4. Write program to 2 numbers and output the largest.
5. Write program to input 3 numbers and output the largest.
Selection
In Selection a statement or block of statements is
executed depending on a condition.
Structure
START
<Statement 1>
IF <Condition> THEN
<Statement 2>
<Statement 3>
ELSE
<Statement 4>
ENDIF
<Statement 5>
END
Selection
In this case Statement1 and Statement5 are
outside the condition so they will be executed
regardless of the condition.

Statement2 and Statement3 will be executed


if the condition is true and Statement 4 Will
only be executed if the condition is false.
Selection
Example
START
Dress up
IF <It is raining> THEN
Carry an umbrella
ELSE
Put on shades
ENDIF
Go to school
END
Selection
Example 2
START
INPUT Number1
INPUT Number2
IF Number1 > Number 2 THEN
OUTPUT Number1 “IS Bigger”
ELSE
OUTPUT Number2 “IS Bigger”
ENDIF
OUTPUT “Thank you”
END
Looking back

Write a program to accept 2 numbers and output the


largest.

Write an algorithm to input 4 numbers and


output the smallest number from the 4.
Write a program to implement you solution
above
Looking back
• Write a program to calculate the area of a rectangle.
Looking back
• Write an algorithm to input 5 Numbers and calculate
the total and average. Output the total and average.

• Implement your algorithm above as a program


Case
• CASE statements allow one out of several branches of code to be executed, depending on the
value of a variable.
CASE statements are written as follows:

CASE OF <identifier>
<value 1> :
<statement1>
<statement2>
...
<value 2> :
<statement1>
<statement2>
...
...
ENDCASE
Case
• An OTHERWISE clause can be the last case:
CASE OF <identifier>
<value 1> :
<statement1>
<statement2>
...
<value 2> :
<statement1>
<statement2>
...
OTHERWISE :
<statement1>
<statement2>
...
ENDCASE
Case
Example

INPUT “Enter Grade”, Grade


CASE of Grade
CASE “A” : OUTPUT “Well done”
CASE “B” : OUTPUT “Well Tried”
CASE “C” : OUTPUT “Fair”
OTHERWISE: OUTPUT “Try again”
ENDCASE
Selection ?
• Write a program to grade marks
Grades
80 – 100  A
60 – 79  B
50 – 59  C
0 – 49  Fail
Research on the select case statement.
? Selection
Given the following grades
80 to 100  A
60 to 79  B
50 to 59  C
40 to 49  D
30 to 39  E
20 to 29  F
0 to 19  U
Write an algorithm to grade students marks
Task
Write an algorithm using CASE to input a mark and grade the mark using the following grades

90 – 100  A*
70 – 89  A
60 – 69  B
50 – 59  C
45 – 49  D
35 – 44  E
0 – 34  U
Extension

Identify an error(s) in the code above, correct the error and


implement the code as a program
Looking back
Write an algorithm using CASE to input a mark and grade the mark using the following grades

80 to 100  Distinction
70 to 79  Merit
60 to 69  Credit
50 to 59  Pass
40 to 49  Resit
0 to 39  Repeat Level

Implement your algorithm as a program in VB using Case


Implement your algorithm as a program in VB using IF THEN ELSE
Iteration - Loop
In iteration a statement or block of statements is
executed for a number of times until a condition
becomes true or false.
Structure
START
<Statement 1>
WHILE <Condition> DO
<Statement 2>
<Statement 3>
ENDWHILE
<Statement 4>
END
Iteration
In this case Statement 1 and Statement 4 are
outside the condition so they will be executed
regardless of the condition.

Statement 2 and Statement 3 will be


executed repeatedly until the condition
becomes false or true.
Iteration
Example
START

Dress up
WHILE <you are hungry> DO
eat some food
drink water
ENDWHILE
Clean up
END
Iteration / loop
There are 3 types of iteration constructs
1. Loop for a specified number of times
2. Test on entry
3. Test on exit

Loop for a specified number of times.


This loop is used when the number of iterations is known before starting the loop, for
example if you are to enter marks for 20 students you know before starting that you
are going to loop 20 times and you use the FOR … NEXT loop
For i = 1 to 20
Input mark
Next i
Test on entry
This loop will test a condition before going into the loop. With this loop statements in the loop

can be executed 0 times if the condition is not true at the start of the loop
Example:

START

Dress up
WHILE <you are hungry> DO
eat some food
drink water
ENDWHILE
Clean up
END
In this case if you are not hungry at the start of the loop you will not enter the loop you go to
ENDWHILE.
Test on exit
This loop will test a condition after executing the statements in the loop at least once. With this
loop, statements in the loop will be executed at least once.

Example:
START
START Dress up
DO
Dress up eat some food
REPEAT drink water
eat some food UNTIL <you are satisfied>
drink water Clean up
END
UNTIL <you are satisfied>
Clean up
END
Pseudocode to output largest out
of 3 inputs
Start
DECLARE Number1, Number2, Number3 : INTEGER
Number1, Number2, Number3 0
INPUT “Enter number 1” Number1
INPUT “Enter number 2” Number2
INPUT “Enter number 3” Number3
IF Number1 > Number2 AND Number1 > Number3 THEN
OUTPUT “Number1 is the largest”
ENDIF
IF Number2 > Number1 AND Number2 > Number3 THEN
OUTPUT “Number2 is the largest”
ENDIF
IF Number3 > Number2 AND Number3 > Number2 THEN
OUTPUT “Number1 is the largest”
ENDIF
Stop
Iteration / loop
There are 3 types of iteration constructs
1. Loop for a specified number of times
2. Test on entry
3. Test on exit

Loop for a specified number of times.


This loop is used when the number of iterations is known before starting the loop, for
example if you are to enter marks for 20 students you know before starting that you
are going to loop 20 times and you use the FOR … NEXT loop
FOR i = 1 to 20
INPUT mark
NEXT i
Write program / algorithm to output numbers from 1 to 10 using
a for loop

Write program / algorithm to output odd numbers from 1 to 19


using a for loop

Write program/algorithm to output numbers 10,9,8,7,…1 using


a for loop
Test on entry
This loop will test a condition before going into the loop. With this loop statements in the loop

can be executed 0 times if the condition is not true at the start of the loop
Example:

START

Dress up
WHILE <you are hungry> DO
eat some food
drink water
ENDWHILE
Clean up
END
In this case if you are not hungry at the start of the loop you will not enter the loop you go to
ENDWHILE.
Write program / algorithm to output numbers from 1 to 10 using
a while (test on entry) loop

Write program / algorithm to output odd numbers from 1 to 19


using a while (test on entry) loop

Write program/algorithm to output numbers 10,9,8,7,…1 using


a while (test on entry) loop
Test on exit
This loop will test a condition after executing the statements in the loop at least once. With this
loop, statements in the loop will be executed at least once.

Example:
START
START Dress up
DO
Dress up eat some food
REPEAT drink water
eat some food UNTIL <you are satisfied>
drink water Clean up
END
UNTIL <you are satisfied>
Clean up
END
Write program / algorithm to output numbers from 1 to 10 using
a REPEAT UNTIL (test on exit) loop

Write program / algorithm to output odd numbers from 1 to 19


using a REPEAT UNTIL (test on exit) loop

Write program/algorithm to output numbers 10,9,8,7,…1 using


a REPEAT UNTIL (test on exit) loop
Pseudocode to output largest out
of 2 inputs
?

Write an algorithm in pseudocode to accept 2


numbers and output the largest.
Flowcharts
(i) Flowcharts
Draw a flowchart to represent the (ii) Draw a flowchart to represent
following pseudocode the following pseudocode
X0
FOR X = 1 to 10
CALL Marks(i)
WHILE X < 10
OUTPUT X CALL Marks(i)
NEXT X XX+1
NEXT X
• Flowcharts

(i) Draw a flowchart to represent the following pseudocode


Flowcharts
X=5
REPEAT
CALL Marks(i)
OUTPUT X
XX+1
UNTIL X = 15
Pseudocode to output largest out
of 3 inputs
?

Write an algorithm in pseudocode to accept 3


numbers and output the largest.
Pseudocode to output largest out
of 10 inputs
?

Write an algorithm in pseudocode to accept


10 numbers and output the largest.
Pseudocode to output smallest
out of 8 inputs
?

Write an algorithm in pseudocode to accept


10 numbers and output the smallest.
Pseudocode to output largest out
of 100 inputs
The program on the previous slide would work when you want to output the largest number from a
limited number of input. Consider the next question;

Write an algorithm in pseudocode to accept


100 numbers and output the largest.
Pseudocode to output largest out
of 100 inputs
Making 100 comparisons will be difficult using the structure of the pseudocode we
have been using. The only way this problem can be solved without running into
logical spaghetti is the use of a loop.

Since the number of numbers to be compared is already known, we will use a FOR
… NEXT loop.
1. Declare variables – in this case 2 variables will be used:
• Number
• Largest

2. Initialise Largest to a very small number e.g. 0 (why ?)


Pseudocode to output largest out
of 100 inputs
The solution
Start Data 56,5,18,70, 30,68
DECLARE Number : INTEGER I Number Largest Output
DECLARE Largest : INTEGER
Largest  0
FOR I  1 to 100
INPUT “ENTER Number” Number
IF Number > Largest THEN
Largest  Number
ENDIF
NEXT I
OUTPUT “The largest number is “ Largest What would have been the output if we had
Stop initialised our variable Largest  90.
Pseudocode to output smallest
out of 10 inputs
Task

Write a algorithm in pseudocode to accept 10


numbers and output the smallest, draw a
trace table and show the result for the
following test data.
Data 91,7,5,9,15,80,60,45,30,71
Rogue data to terminate a loop
The for loop is only applicable in situations where the number input data is known
beforehand. In situations where the number of input data is not known rogue data
can be used to terminate the input. For example a program to accept a set of
numbers and output the largest can be structured as follows using -1 as rogue data.
Start Data 7,67,18,50,30,80,-1,88,90
DECLARE Number, Largest : INTEGER Number Largest Output
Largest 0
INPUT Number
WHILE Number <> -1 DO
IF Number > Largest THEN
Largest  Number
ENDIF
INPUT “Enter number “ Number
ENDWHILE
OUTPUT “The largest number is” Largest
Read this section of code that inputs the ages of people entering an event. The input sequence is
ended by inputting a negative value for age. The code outputs the number of people at the event
over the age of 18.
Num18 = 0
INPUT Age
WHILE Age >= 0 DO
IF Age > =18 THEN
Num18 = Num18 + Age
ENDIF
ENDWHILE
PRINT Num18 - Age
There are four errors in this code. Locate these errors and suggest code correction
to remove each error.
START
Complete the trace table for the input values 4, 3, −1:

INPUT A OUTPUT B A B C OUTPUT

IS Yes B A
A > 0 ? B B + A C C – 1
C A

No
IS
C <= 1 ?
OUTPUT Yes
'Exit'
No

END
(a) Rewrite the following pseudocode algorithm using a
WHILE … DO … ENDWHILE loop.
INPUT Num
FOR Counter ← 1 TO 12
Num ← Num * Counter
A[Counter] ← Num
NEXT

(b) Explain the differences between a WHILE … DO …


ENDWHILE and a REPEAT … UNTIL loop.
An algorithm has been written in pseudocode to input 100 numbers, select and print the largest number and smallest number.

(a) Find the four errors in the pseudocode and


suggest a correction for each error.

(b) Show how you would change the corrected


algorithm to total the numbers and print the
total.
Use a variable Total.
String manipulation

String manipulation here


Data structures
A computer system needs to be presented with the correct data structure for it to perform the
correct operations on data.
Data structures
A computer system needs to be presented with the correct data structure for it to perform the
correct operations on data.
Array
An array is a se of homogeneous elements referred to by a single data name. Items in an array
need to be related for correct manipulation of the data.

A one dimensional array is the simplest way of representing related data in a table format for
example cities in Zimbabwe can be represented as follow

0 1 2 3 4 5
Cities Harare Bulawayo Mutare Gweru Chitungwiza Kwekwe

Cities(0) = Harare
Cities(3) = Gweru
Cities (1+1) = ?
Arrays
Before using an array, one must consider the type of data to be stored and also the size of the
array which is determined by the amount of data to be stored. An appropriate meaningful name
related to the data to be stored should be given. In the example given in the previous slide the
name Cities was given because the array stores cities.

Usually arrays begin at element 0 so the maximum number of elements to be stored is 1 more
than the actual number.
Arrays
Declaring an array

To declare an array cities to store 6 cities we use the following declaration.

DECLARE Cities[0:5] AS STRING / DECLARE Cities[5] AS STRING


The declaration here is Cities[0:5] /Cities[5] because we start at element 0 so the 5 th slot will
store the 6th city.

It is possible to declare an array in some programming languages by declaring the lower limit
and the upper limit for example Cities[1:6], this forces the computer to set the lower bound as 1
and the upper bound as 6 and in such a situation you cannot add an element at position 7 or 0
because these positions are outside the bounds set in the declaration.

Research on programming languages which allow a programmer to set the bounds and those
which does not allow setting of the bounds.
Two dimensional arrays
?
Array Result is a global 2D array of type STRING. It has 100
rows and 2 columns.

Write pseudocode to declare the array Result and to initialise all


elements to zero.
Two dimensional arrays
A two dimensional array has rows and columns
For example the array

Is a 5 x 4 dimensional array

To declare the array we will use the format


DECLARE <identifier> [<lbound1>:<ubound1>,<lbound2>:<ubound2>]

Eg DECLARE StudentMarks[1:5 , 1:4] AS INTEGER

Which reads declare array called StudentMarks which is 5 x 4 and is Integer type
Soccer
DECLARE Sport[1:4] OF STRING
Basketball
Sport[1]  “Soccer” Hockey
Sport[2]  “Basketball” Tennis

Sport[3]  “Hockey”
Sport[4]  “Tennis”
OR
For I = 1 to 4
OUTPUT “Enter sport Name”
Sport[I]  INPUT Sport
Next I
Adding data to an array
There are three ways to add data to an array.
1. Add on declaration – this method is applicable when the data to be added to the
array is limited (not many records) and the added items will be added to the
array every time the array is created and will stay there.
2. Manually add after declaration – Just like in 1 (add on declaration) this method is
for arrays with few items.
3. Interactive add – A dynamic method which requires data to be entered every
time the program is run. This is suitable for simulating adding data to large
arrays e.g. an array with over 20 items.
Adding on declaration
To add on Declaration

DECLARE ARRAY : Towns() OF STRING = {“Harare”, “Bulawayo”, “Mutare”,


“Gweru”}
Task
Using pseudocode
• Declare an array StudentMarks of integer type
• add 10 arbitrary marks to the array.

Remember - Numeric data is not put in quotes

In Visual Basic
• Declare an array StudentMarks of integer type
• add 10 arbitrary marks to the array.
• Create a loop to list the 10 marks
Manually adding data to
an array
Adding data manually to an array

DECLARE Towns : ARRAY() OF STRING


Towns(0) “Harare”
Towns(1)  “Bulawayo”
Towns(2)  “Mutare”
Towns(3)  “Gweru”
Using a loop to add data
Using a loop to add data to an array

DECLARE ARRAY : Towns() OF STRING


DECLARE Town as String
For I = 1 to 100
Towns(I)  INPUT “Enter town”, Town
Next I
Task
Declare an array StudentMarks of integer type and 50 arbitrary marks.

Remember - Numeric data is not put in quotes


Task
Using pseudocode
• Declare an array Cars of String type
• add 5 arbitrary Car models to the array.

In Visual Basic
• Declare an array Cars of String type
• add 5 arbitrary models to the array.
• Create a loop to list the 5 models
Task
Re-write the task in the previous slide using a REPEAT loop
Re-write the task in the previous slide using a REPEAT loop
Task
Declare an array StudentMarks of integer type and 50 arbitrary marks.

Remember - Numeric data is not put in quotes


looking back
Using pseudocode,

1. Declare an array called Schools which will store 10 schools


2. Initialize the array with spaces (“ ”)
3. Assign 10 schools to the array.
4. Output the contents of the array

Implement the solution above in visual basic.


Task
Write a program to create an array called marks and assign the following marks on
declaration {67,87,23,90,65,38,73,66,82,39}

• Sum the marks in the array


• Output the
– Sum
– Average
– Highest
– Lowest
Arrays <3
Sorting data in an array
To sort data in an array the following steps are followed
1. Read the first element in the array (eg Cities(0) which is Harare)
2. Read the next element in the array (eg Cities(1) which is Bulawayo)
3. Compare the two elements (i.e IF Cities(0) > Cities(1) ? – in this case it is true)
4. If it is true then swap the elements (the swapping process is never easy, we will see it in the next slide)
5. Proceed by comparing the current contents of Cities(1) to contents of Cities(2)
6. Continue the comparisons until the last element.

This one pass process described in steps 1 to 6 does not produce a perfect sort, the process has to be
repeated (n-1) times to fully sort the array where n is highest index number in the array

? How many passes are needed to make a perfect sort for the cities array? (containing 6 cities)
? How many passes are needed to make a perfect sort for the marks array? (Containing 10 marks)
looking back
Using pseudocode,

1. Declare an array called Clubs which will store 10 clubs at Arundel


2. Initialize the array with spaces (“ ”)
3. Assign 10 clubs to the array.
4. Output the contents of the array

Implement the solution above in visual basic.


Arrays
Swapping data elements
Like I said in the previous slide swapping data is never easy

Lets consider the following segment of an algorithm to swap the cities


Remember

IF Cities[0] > Cities[1] THEN


Cities[0] Cities[1]
Cities[1] Cities[0]
ENDIF

? What will be the contents of Cities[0]


? What will be the contents of Cities[1]
Arrays

IF Cities[0] > Cities[1] THEN


0 1
Cities[0] Cities[1]  gives Bulawayo Bulawayo

0 1
Cities[1] Cities[0]  gives Bulawayo Bulawayo
ENDIF

So we end up with Bulawayo in Cities[0] and Bulawayo in cities[1] WHY?


Because when executing Cities[1]  Cities[0] the contents of cities[0] would
have already changed to Bulawayo and that’s the value which will be copied
to Cities[1]
Arrays
For us to have a perfect swap we introduce a dummy variable called TEMP which will hold the contents of
Cities(0) during the swap to avoid over-writting the contents. Consider the following snippet of an algorithm.

IF Cities[0] > Cities[1] THEN


TEMP Cities[0]
Cities[0]  Cities[1]
Cities[1] TEMP
ENDIF
0 1 TEMP
TEMP Cities[0] gives Harare Bulawayo Harare

0 1 TEMP
Cities[0]  Cities[1] gives
Bulawayo Bulawayo Harare

0 1 TEMP
Cities[1]  TEMP gives
Bulawayo Harare Harare
Arrays
However for proper running of arrays we use loops to assign values and in this case the number of times a loop
is going to be executed is known so the most appropriate type of a loop to use is the FOR… NEXT loop which is
going to run (n-1) times where n is the last index number for the array.

Consider the loop


FOR x = 0 to 4
IF Cities [x] > Cities [x+1] THEN // x = 0 so Cities [x] = Cities [0] = Harare and Cities[x+1] = Cities[1]
TEMP Cities(x)
Cities [x]  Cities [x+1]
Cities [x+1] TEMP
ENDIF
NEXT x

? Why did we run the loop n-1 times (why FOR x = 0 to 4 and not FOR x = 0 to 5)
Arrays
To complete our sorting we use nested loops, with the outer loop defining the number of passes we are
supposed to make. For us to achieve a complete sort we have to do (n-1) passes. So the following algorithm will
input the 6 cities and then sort them.

DECLARE Cities : ARRAY [0:5] OF STRING


FOR I = 0 to 5 // loop to input the cities
OUTPUT “Enter city”
Cities[I]  INPUT City
NEXT I
FOR T = 0 to 4 // outer sorting loop for number of passes
FOR x = 0 to 4 //inner sorting loop for the actual sorting
IF Cities(x) > Cities [x+1] THEN
TEMP Cities [x]
Cities [x]  Cities [x+1]
Cities [x+1] TEMP
ENDIF
NEXT x
NEXT T
Arrays
Original Sorted

1 2 3 4 (after 1
Pass)
Harare Bulawayo Bulawayo Bulawayo Bulawayo Bulawayo

Bulawayo Harare Harare Harare Harare Harare

Mutare Mutare Mutare Gweru Gweru Gweru

Gweru Gweru Gweru Mutare Chitungwiza Chitungwiza

Chitungwiza Chitungwiza Chitungwiza Chitungwiza Mutare Kwekwe

Kwekwe Kwekwe Kwekwe Kwekwe Kwekwe Mutare

The sorted list is not a perfectly sorted list


? How many more passes are needed to make a perfect sort
Homework
Write down the locations of these schools

Array name: HarareSchools Array name: BulawayoSchools

0 1 2 3 4 0 1 2 3 4
Arundel Chisipite Petra Byo Convent
Homework
Write down the locations of these schools

Array name: HarareSchools Array name: BulawayoSchools

0 1 2 3 4 0 1 2 3 4
0 Arund Gateway 0 Girls
el College
1 Byo Petra
1 Chisi Convent
pite
2 Falco
2 Heritage n
3 Conv 3 CBC
ent

Create the 2 arrays in VB and enter the schools. Output the schools.
Task 1
Using 2 D arrays create the following
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Task 2
Using 2 D arrays create the following * * * * * * * * * *

* * * * * * * * *

* * * * * * * *

* * * * * * *

* * * * * *

* * * * *

* * * *

* * *

* *

*
Task 3
Using 2 D arrays create the following *

* * *

* * * * *

* * * * * * *

* * * * * * * * *

* * * * * * * * * * *

* * * * * * * * *

* * * * * * *

* * * * *

* * *

*
Homework
Write an algorithm to create array called marks which will hold marks for 10 students. The algorithm must
(a) Declare the array [4]
(b) have a loop(s) to enter the marks [4]
(c) Have a loop(s) to sort the marks in descending order (a complete perfect sort) [8]
(d) Have a loop to output the results [4]
Task

• Create an array and assign 10 students on declaration

• Sort the array in ascending order.


Two dimensional arrays
A two dimensional array has rows and columns
For example the array

Is a 5 x 4 dimensional array

To declare the array we will use the conventional way of declaring arrays in pseudocode and for consistency
we will stick to this declaration.
DECLARE <identifier> : ARRAY[<lbound1>:<ubound1>,<lbound2>:<ubound2>]
OF <datatype>

Eg DECLARE StudentMarks : ARRAY [0:4 , 0:3] OF STRING

Which reads declare array called StudentMarks which is 5 x 4 and is of string type
Two dimensional arrays
?
Array Result is a global 2D array of type STRING. It has 100
rows and 2 columns.

Write pseudocode to declare the array Result and to initialise all


elements to zero.
Answer: DECLARE Result : ARRAY [0:99,0:1] OF STRING / DECLARE Result : ARRAY [1:100, 1:2] OF STRING
FOR X = 0 to 1 1 1
FOR I = 0 to 99
1 1
Result [ I , X ]  1
1 1
NEXT I
NEXT X 1 1
Two dimensional arrays
Task

- Write pseudocode to declare a 6 x 8 2D array Marks of type Integer and to


initialise all elements to zero.
- Write pseudocode to enter marks into the array.
- Write pseudocode to output the marks.

Create a program to implement the task above.


Two dimensional arrays

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Create a program code to print the array above.


Two dimensional arrays

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8

Create a program code to print the array above.


Two dimensional arrays

34 25 85 41 14 32
23 52 14 78 52 45
63 42 15 52 63 58
74 52 52 62 85 95
75 74 85 25 36 36
25 62 85 85 41 95
14 52 62 65 25 87
95 24 25 35 62 41

Create a program code to swap the contents of column 1 with 6, 2 with 5 and 3 with
4.
String manipulation
String manipulation

- Arrays can be used together with string manipulation operations to carry out
many tasks.

Examples of string manipulation functions

MID(ThisString : STRING, x : INTEGER, y : INTEGER) RETURNS STRING


• returns a string of length y starting at position x from ThisString
• Example: MID("ABCDEFGH", 2, 3) returns "BCD"
Homework
Write a program to create array called Students which will hold marks for 10 students.
Write a program to create array called marks which will hold marks for 10 students.

(a) Declare the arrays and assign the Names and marks on entry
[4]
(c) Have a loop(s) to sort the marks and student names in descending order (a complete perfect
sort)
[8]
(d) Have a loop to output the sorted names and marks (ensure a student stays with her mark)
[4]

You might also like