2. Module Description
• This module is an introduction to programming, program design
and algorithms. Students are introduced to a structured procedural
programming language and to commonly used algorithms and their
implementation.
– This module assumes no prior knowledge of programming or algorithms.
– The aims of this module are to:
– Teach the fundamentals of procedural programming
– Teach the principles of good program design, implementation,
documentation and testing.
– Teach the theory and application of elementary algorithms and data
structures.
3. Learning Outcomes
On Completion of this module, the learner will be able to
• Design and write computer elementary programs in a structured procedural
language.
• Use a text editor with command line tools and simple Integrated
Development Environment (IDE) to compile, link and execute program code.
• Divide a computer program into modules.
• Test computer programs to ensure compliance with requirements.
• Implement elementary algorithms and data structures in a procedural
language.
4. Indicative Syllabus
• Introduction: What is a program? Source code. Machine code.
Editing, Compiling, Linking Debugging. Use of an Integrated
Development Environment (IDE).
• Basic Data Types: integer, floating-point and character data and
variables.
• Basic Input-Output: Display data on a screen. Input data from the
keyboard.
• Programming Structures: Conditional statements: Boolean values
and expressions, logical and relational operators, if-statement,
case-statement, compound conditional statements.
5. Indicative Syllabus
• Iterative constructs: while-statements, for-statements and
nested control statements.
• Structured Programming: functions, parameter passing,
returning values.
• Introduction to Data Structures: single-dimensional arrays,
two-dimensional arrays, dynamically allocated arrays
6. Indicative Syllabus
• Basic Algorithms: summation, counting, numeric operations,
swapping, maximum and minimum, simple array manipulation.
• Elementary Sorting Algorithms: Internal Sorting. Exchange sort.
Interchange sort. Bubble sort. Shaker sort. Insertion sort.
• Testing and debugging: Objectives and principles of testing.
Choosing appropriate test data. Simple debugging using a
program trace.
• Documentation: Style guidelines.
13. Algorithms
• An Algorithm is a series of instructions
• Examples of algorithms include
– Musical scores
– Knitting patterns Row 1: SL 1, K8, K2 tog, K1, turn
– Recipies
14. Algorithms
• Problem Solving
– Analyse Problem (Analysis)
– Develop Algorithm (Design)
– Convert into programming language (Development)
28. Some Challenges of Blended Learning
• Technical Issues
• Motivation of the Students
• Student Participation
• Ensuring Interactive of lessons
• Organisational Alignment
31. Pseudocode
• The first thing we do when designing a program is to decide on
a name for the program.
32. Pseudocode
• The first thing we do when designing a program is to decide on
a name for the program.
• Let’s say we want to write a program to calculate interest, a
good name for the program would be
CalculateInterest.
33. Pseudocode
• The first thing we do when designing a program is to decide on
a name for the program.
• Let’s say we want to write a program to calculate interest, a
good name for the program would be
CalculateInterest.
• Note the use of CamelCase.
34. Pseudocode
• The first thing we do when designing a program is to decide on
a name for the program.
• Let’s say we want to write a program to calculate interest, a
good name for the program would be
CalculateInterest.
• Note the use of CamelCase.
43. Top-Down Design
• Top-Down Design (also known as stepwise design) is breaking
down a problem into steps.
• In Top-down Design an overview of the problem is described
first, specifying but not detailing any first-level sub-steps.
• Each sub-step is then refined in yet greater detail, sometimes
in many additional sub-steps, until the entire specification is
reduced to basic elements.
45. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
46. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
47. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
48. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
49. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
50. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
51. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
52. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
53. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
54. Example
1. Organise everything together
2. Plug in kettle
3. Put teabag in cup
4. Put water into kettle
5. Turn on kettle
6. Wait for kettle to boil
7. Add boiling water to cup
8. Remove teabag with spoon/fork
9. Add milk and/or sugar
10. Serve
55. Example : Step-wise Refinement
Step-wise refinement of step 1 (Organise everything together)
1.1 Get a cup
1.2 Get tea bags
1.3 Get sugar
1.4 Get milk
1.5 Get spoon/fork.
56. Example : Step-wise Refinement
Step-wise refinement of step 2 (Plug in kettle)
2.1 Locate plug of kettle
2.2 Insert plug into electrical outlet
57. Example : Step-wise Refinement
Step-wise refinement of step 3 (Put teabag in cup)
3.1 Take teabag from box
3.2 Put it into cup
58. Example : Step-wise Refinement
Step-wise refinement of step 4 (Put water into kettle)
4.1 Bring kettle to tap
4.2 Put kettle under water
4.3 Turn on tap
4.4 Wait for kettle to be full
4.5 Turn off tap
59. Example : Step-wise Refinement
Step-wise refinement of step 5 (Turn on kettle)
5.1 Depress switch on kettle
63. Pseudocode
• When we write programs, we assume that the computer
executes the program starting at the beginning and working its
way to the end.
• This is a basic assumption of all algorithm design.
64. Pseudocode
• When we write programs, we assume that the computer
executes the program starting at the beginning and working its
way to the end.
• This is a basic assumption of all algorithm design.
• We call this SEQUENCE.
65. Pseudocode
• In Pseudo code it looks like this:
Statement1;
Statement2;
Statement3;
Statement4;
Statement5;
Statement6;
Statement7;
Statement8;
66. Pseudocode
• For example, for making a cup of tea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk and/or sugar;
Serve;
67. Pseudocode
• Or as a program:
PROGRAM MakeACupOfTea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk and/or sugar;
Serve;
END.
68. Pseudocode
• Or as a program:
PROGRAM MakeACupOfTea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk and/or sugar;
Serve;
END.
69. Organise everything together
Plug in kettle
Put teabag in cup
Put water into kettle
Turn on kettle
Wait for kettle to boil
Add boiling water to cup
Remove teabag with spoon/fork
Add milk and/or sugar
Serve
70. Organise everything together
Plug in kettle
Put teabag in cup
Put water into kettle
Turn on kettle
Wait for kettle to boil
Add boiling water to cup
Remove teabag with spoon/fork
Add milk and/or sugar
Serve
START
END
71. Pseudocode
• So let’s say we want to express the following algorithm:
– Read in a number and print it out.
85. Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x <- 5
means “X gets the value 5”
or “X is assigned 5”
86. Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x <- 5;
means “X gets the value 5”
or “X is assigned 5”
87. Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x <- 5;
means “X gets the value 5”
or “X is assigned 5”
X
88. Variables
• In programming, we tell the computer the value of a variable
• So, for example,
x <- 5;
means “X gets the value 5”
or “X is assigned 5”
X
5
89. Variables
• And later we can say something like:
x <- 8;
means “X gets the value 8”
or “X is assigned 8”
90. Variables
• If we want to add one to a variable:
x <- x + 1;
means “increment X”
or “X is incremented by 1”
X(new)
5
X(old)
4
+1
91. Variables
• We can create a new variable Y
y <- x;
means “Y gets the value of X”
or “Y is assigned the value of X”
Y
X
6
6
92. Variables
• We can also say:
y <- x + 1;
means “Y gets the value of x plus 1”
or “Y is assigned the value of x plus 1”
Y
X
6
7
+1
93. Variables
• All of these variables are integers
• They are all whole numbers
94. Variables
• Let’s look at numbers with decimal points:
P <- 3.14159;
means “p gets the value of 3.14159”
or “p is assigned the value of 3.14159”
95. Variables
• We should really give this a better name:
Pi <- 3.14159;
means “Pi gets the value of 3.14159”
or “Pi is assigned the value of 3.14159”
96. Variables
• We can also have single character variables:
Vitamin <- ‘B’;
means “Vitamin gets the value of B”
or “Vitamin is assigned the value of B”
97. Variables
• We can also have single character variables:
RoomNumber <- ‘2’;
means “RoomNumber gets the value of 2”
or “RoomNumber is assigned the value of 2”
98. Variables
• We can also have a string of characters:
Pet <- “Dog”;
means “Pet gets the value of Dog”
or “Pet is assigned the value of Dog”
99. Variables
• We also have a special type, called BOOLEAN
• It has only two values, TRUE or FALSE
IsWeekend <- FALSE;
means “IsWeekend gets the value of FALSE”
or “IsWeekend is assigned the value of FALSE”
100. Pseudocode
• So let’s say we want to express the following algorithm:
– Read in a number and print it out.
112. Do you wish to print a receipt?
< YES NO >
In the interests of preserving the
environment, we prefer not to print a
receipt, but if you want to be a jerk, go
ahead.
< PRINT RECEIPT CONTINUE >
113. Selection
• What if we want to make a choice, for example, do we want to
add sugar or not to the tea?
114. Selection
• What if we want to make a choice, for example, do we want to
add sugar or not to the tea?
• We call this SELECTION.
115. IF Statement
• So, we could state this as:
IF (sugar is required)
THEN add sugar;
ELSE don’t add sugar;
ENDIF;
116. IF Statement
• Adding a selection statement in the program:
PROGRAM MakeACupOfTea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk;
IF (sugar is required)
THEN add sugar;
ELSE do nothing;
ENDIF;
Serve;
END.
117. IF Statement
• Adding a selection statement in the program:
PROGRAM MakeACupOfTea:
Organise everything together;
Plug in kettle;
Put teabag in cup;
Put water into kettle;
Wait for kettle to boil;
Add water to cup;
Remove teabag with spoon/fork;
Add milk;
IF (sugar is required)
THEN add sugar;
ELSE do nothing;
ENDIF;
Serve;
END.
118. IF Statement
• Or, in general:
IF (<CONDITION>)
THEN <Statements>;
ELSE <Statements>;
ENDIF;
119. IF Statement
• Or to check which number is biggest:
IF (A > B)
THEN Print A;
ELSE Print B;
ENDIF;
120. Pseudocode
• So let’s say we want to express the following algorithm:
– Read in a number, check if it is odd or even.
122. Pseudocode
• We can skip the ELSE part if there is nothing to do in the
ELSE part.
• So:
IF (sugar is required)
THEN add sugar;
ELSE don’t add sugar;
ENDIF;
130. Pseudocode
• So let’s say we want to express the following algorithm to
print out the bigger of two numbers:
– Read in two numbers, call them A and B. Is A is bigger than B, print out A,
otherwise print out B.
138. Pseudocode
• So let’s say we want to express the following algorithm to
print out the bigger of three numbers:
– Read in three numbers, call them A, B and C.
• If A is bigger than B, then if A is bigger than C, print out A, otherwise print out C.
• If B is bigger than A, then if B is bigger than C, print out B, otherwise print out C.
151. Boolean Logic
• You may have seen Boolean logic in another module already,
for this module, we’ll look at three Boolean operations:
– AND
– OR
– NOT
152. Boolean Logic
• Boolean operators are used in the conditions of:
– IF Statements
– CASE Statements
– WHILE Loops
– FOR Loops
– DO Loops
– LOOP Loops
153. Boolean Logic
• AND Operation
– The AND operation means that both parts of the condition must be
true for the condition to be satisfied.
– A=TRUE, B=TRUE => A AND B = TRUE
– A=FALSE, B=TRUE => A AND B = FALSE
– A=TRUE, B=FALSE => A AND B = FALSE
– A=FALSE, B=FALSE => A AND B = FALSE
155. Boolean Logic
PROGRAM GetGrade:
Read Result;
IF (A = 5 AND Age[Index] < Age[Index+1])
THEN PRINT “A is 5”;
ENDIF;
END.
• Both A=5 and Age[Index] < Age[Index+1] must be
TRUE to do the THEN part of the statement.
156. Boolean Logic
• OR Operation
– The OR operation means that either (or both) parts of the condition
must be true for the condition to be satisfied.
– A=TRUE, B=TRUE => A OR B = TRUE
– A=FALSE, B=TRUE => A OR B = TRUE
– A=TRUE, B=FALSE => A OR B = TRUE
– A=FALSE, B=FALSE => A OR B = FALSE
158. Boolean Logic
PROGRAM GetGrade:
Read Result;
IF (A = 5 OR Age[Index] < Age[Index+1])
THEN PRINT “A is 5”;
ENDIF;
END.
• Either or both of A=5 and Age[Index] <
Age[Index+1] must be TRUE to do the THEN part of the
statement.
159. Boolean Logic
• NOT Operation
– The NOT operation means that the outcome of the condition is
inverted.
– A=TRUE => NOT(A) = FALSE
– A=FALSE => NOT(A) = TRUE
161. Boolean Logic
PROGRAM GetGrade:
Read Result;
IF (NOT (A = 5))
THEN PRINT “A is 5”;
ENDIF;
END.
• Only when A is not 5 the program will go into the THEN part of
the IF statement, when A is 5 the THEN part is skipped.
167. CASE Statement
Read Answer;
IF (Answer = ‘A’)
THEN Print “That is incorrect”;
ELSE IF (Answer = ‘B’)
THEN Print “That is incorrect”;
ELSE IF (Answer = ‘C’)
THEN Print “That is Correct”;
ELSE IF (Answer = ‘D’)
THEN Print “That is incorrect”;
ELSE Print “Bad Option”;
END IF;
END IF;
END IF;
END IF;
168. CASE Statement
PROGRAM MultiChoiceQuestion:
Read Answer;
IF (Answer = ‘A’)
THEN Print “That is incorrect”;
ELSE IF (Answer = ‘B’)
THEN Print “That is incorrect”;
ELSE IF (Answer = ‘C’)
THEN Print “That is Correct”;
ELSE IF (Answer = ‘D’)
THEN Print “That is incorrect”;
ELSE Print “Bad Option”;
ENDIF;
ENDIF;
ENDIF;
ENDIF;
END.
169. CASE Statement
Read Answer;
CASE OF Answer
‘A’ :Print “That is incorrect”;
‘B’ :Print “That is incorrect”;
‘C’ :Print “That is Correct”;
‘D’ :Print “That is incorrect”;
OTHER:Print “Bad Option”;
ENDCASE;
170. CASE Statement
PROGRAM MultiChoiceQuestion:
Read Answer;
CASE OF Answer
‘A’ :Print “That is incorrect”;
‘B’ :Print “That is incorrect”;
‘C’ :Print “That is Correct”;
‘D’ :Print “That is incorrect”;
OTHER:Print “Bad Option”;
ENDCASE;
END.
171. CASE Statement
• Or, in general:
CASE OF Value
Option1: <Statements>;
Option2: <Statements>;
Option3: <Statements>;
Option4: <Statements>;
OTHER : <Statements>;
ENDCASE;
173. CASE Statement
Read Result;
CASE OF Result
Result => 70 :Print “You got a first”;
Result => 60 :Print “You got a 2.1”;
Result => 50 :Print “You got a 2.2”;
Result => 40 :Print “You got a 3”;
OTHER :Print “Dude, you failed”;
ENDCASE;
174. CASE Statement
PROGRAM GetGrade:
Read Result;
CASE OF Result
Result => 70 :Print “You got a first”;
Result => 60 :Print “You got a 2.1”;
Result => 50 :Print “You got a 2.2”;
Result => 40 :Print “You got a 3”;
OTHER :Print “Dude, you failed”;
ENDCASE;
END.
177. WHILE Loop
• Consider the problem of searching for an entry in a phone
book with only SELECTION:
178. WHILE Loop
Get first entry;
IF (this is the correct entry)
THEN write down phone number;
ELSE get next entry;
IF (this is the correct entry)
THEN write done entry;
ELSE get next entry;
IF (this is the correct entry)
……………
180. WHILE Loop
Get first entry;
Call this entry N;
WHILE (N is NOT the required entry)
DO Get next entry;
Call this entry N;
ENDWHILE;
181. WHILE Loop
PROGRAM SearchForEntry:
Get first entry;
Call this entry N;
WHILE (N is NOT the required entry)
DO Get next entry;
Call this entry N;
ENDWHILE;
END.
182. WHILE Loop
• Or, in general:
WHILE (<CONDITION>)
DO <Statements>;
ENDWHILE;
183. WHILE Loop
• So let’s say we want to express the following algorithm:
– Print out the numbers from 1 to 5
188. WHILE Loop
• So let’s say we want to express the following algorithm:
– Calculate the factorial of any value
189. WHILE Loop
• So let’s say we want to express the following algorithm:
– Calculate the factorial of any value
– Remember:
– 5! = 5*4*3*2*1
– 7! = 7*6 *5*4*3*2*1
– N! = N*(N-1)*(N-2)*…*2*1
190. WHILE Loop
PROGRAM Factorial:
Get Value;
Total <- 1;
WHILE (Value != 0)
DO Total <- Value * Total;
Value <- Value - 1;
ENDWHILE;
Print Total;
END.
198. FOR Loop
• Or, in general:
FOR Variable IN Range
DO <Statements>;
ENDFOR;
199. DO Loop
• The WHILE loop can execute any number of times,
including zero times.
• If we are writing a program, and we know that the loop
we are using will be executed at least once, we could
consider using a DO loop instead.
200. DO Loop
PROGRAM MenuOptions:
DO
Print “****** MENU OPTIONS ******”;
Print “1) Input Data”;
Print “2) Delete Data”;
Print “3) Print Report”;
Print “9) Exit”;
Get Value;
WHILE (Value != 9)
END.
201. DO Loop
• Or, in general:
DO
<Statements>;
WHILE (<Condition>)
202. LOOP Loop
• The LOOP loop is one that has no condition, so it is an
infinite loop. But it does include an EXIT command to
break out of the loop if needed.
207. Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
208. Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
209. Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
210. Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
– Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For
7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime.
211. Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
– Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For
7, if 6, 5, 4, 3, and 2 give a remainder then 7 is prime.
– So all we need to do is divide 7 by all numbers less than it but greater than one, and if
any of them have no remainder, we know it’s not prime.
212. Prime Numbers
• So,
• If the number is 7, as long as 6, 5, 4, 3, and 2 give a
remainder, 7 is prime.
• If the number is 9, we know that 8, 7, 6, 5, and 4, all give
remainders, but 3 does not give a remainder, it goes
evenly into 9 so we can say 9 is not prime
213. Prime Numbers
• So remember,
– if the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder,
7 is prime.
• So, in general,
– if the number is A, as long as A-1, A-2, A-3, A-4, ... 2 give a
remainder, A is prime.
214. Prime Numbers
• First Draft:
PROGRAM CheckPrime:
READ A;
B <- A-1;
WHILE (B != 1)
DO {KEEP CHECKING IF A/B DIVIDES EVENLY}
ENDWHILE;
IF (ANY TIME THE DIVISION WAS EVEN)
THEN Print “It is not prime”;
ELSE Print “It is prime”;
ENDIF;
END.
215. Prime Numbers
PROGRAM CheckPrime:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
IF (IsPrime = FALSE)
THEN Print “Not Prime”;
ELSE Print “Prime”;
ENDIF;
END.
221. Fibonacci Numbers
• The Fibonacci numbers are
numbers where the next number
in the sequence is the sum of the
previous two.
• The sequence starts with 1, 1,
• And then it’s 2
• Then 3
• Then 5
• Then 8
• Then 13
222. Leonardo Bonacci (aka Fibonacci)
• Born 1170.
• Born in Pisa, Italy
• Died 1250.
• An Italian mathematician, considered
to be "the most talented Western
mathematician of the Middle Ages".
• Introduced the sequence of Fibonacci
numbers which he used as an example
in Liber Abaci.
223. Fibonacci Numbers
PROGRAM FibonacciNumbers:
READ A;
FirstNum <- 1;
SecondNum <- 1;
WHILE (A != 2)
DO Total <- SecondNum + FirstNum;
FirstNum <- SecondNum;
SecondNum <- Total;
A <- A – 1;
ENDWHILE;
Print Total;
END.
226. • Rather than have to store every character in a file (e.g. an MP3
file), it would be great if we could find a way of reducing the
length of the file to allow it to be stored in a smaller space.
Data Compression
227. • Also Rather than have to send every character in a message, it
would be great if we could find a way of reducing the length of
the message to allow it to be transmitted quicker.
Data Compression
228. • Let’s look at an example.
The rain in Spain lies mainly in the plain
Data Compression
229. Data Compression
• The a total of 42 characters (including 8 spaces)
The rain in Spain lies mainly in the plain
230. Data Compression
• The a total of 42 characters (including 8 spaces)
The rain in Spain lies mainly in the plain
231. Data Compression
• Lets replace the word “the” with the number 1.
The rain in Spain lies mainly in the plain
232. Data Compression
• Lets replace the word “the” with the number 1.
1 rain in Spain lies mainly in 1 plain
the =1
233. Data Compression
• Lets replace the word “the” with the number 1.
• We’ve reduced the of characters to 38.
1 rain in Spain lies mainly in 1 plain
the =1
234. Data Compression
• Lets replace the letters “ain” with the number 2.
1 rain in Spain lies mainly in 1 plain
the =1
235. Data Compression
• Lets replace the letters “ain” with the number 2.
• We’ve reduced the of characters to 30.
1 r2 in Sp2 lies m2ly in 1 pl2
the =1
ain =2
236. Data Compression
• Lets replace the letters “in” with the number 3.
1 r2 in Sp2 lies m2ly in 1 pl2
the =1
ain =2
237. Data Compression
• Lets replace the letters “in” with the number 3.
• We’ve reduced the of characters to 28.
1 r2 3 Sp2 lies m2ly 3 1 pl2
the =1
ain =2
in = 3
238. Data Compression
• Now lets say 1 means “the ”, so it’s “the” and a space
1 r2 3 Sp2 lies m2ly 3 1 pl2
the =1
ain =2
in = 3
239. Data Compression
• Now lets say 1 means “the ”, so it’s “the” and a space
• We’ve reduced the of characters to 26.
1r2 3 Sp2 lies m2ly 3 1pl2
the =1
ain =2
in = 3
240. Data Compression
• Now lets say 3 means “in ”, so it’s “in” and a space
1r2 3 Sp2 lies m2ly 3 1pl2
the =1
ain =2
in = 3
241. Data Compression
• Now lets say 3 means “in ”, so it’s “in” and a space
• We’ve reduced the of characters to 24.
1r2 3Sp2 lies m2ly 31pl2
the =1
ain =2
in = 3
242. Data Compression
• So that’s 24 characters for a 42 character message, not bad.
The rain in Spain lies mainly in the plain
1r2 3Sp2 lies m2ly 31pl2
the =1
ain =2
in = 3
244. Data Compression
• Let’s try a different example. Let’s say we are sending a list of
jobs, with each item on the list is 10 characters long.
• Bookkeeper
• Teacher---
• Porter----
• Nurse-----
• Doctor----
245. Data Compression
• Rather than sending the spaces we could just say how long
they are:
• Bookkeeper
• Teacher---
• Porter----
• Nurse-----
• Doctor----
246. Data Compression
• Rather than sending the spaces we could just say how long
they are:
• Bookkeeper
• Teacher---
• Porter----
• Nurse-----
• Doctor----
• Bookkeeper
• Teacher3-
• Porter4-
• Nurse5-
• Doctor4-
248. PROGRAM CompressExample:
Get Current Character;
WHILE (NOT End_of_Line)
DO Get Next Character;
IF (Current Character != Next Character)
THEN Get next char, and set current to next;
Write out Current Character;
ELSE
Keep looping while the characters match;
Keep counting;
Get next char, and set current to next;
When finished write out Counter;
Write out Current Character;
Reset Counter;
ENDIF;
ENDWHILE;
END.
249. PROGRAM CompressExample:
char Current_Char, Next_char;
Current_Char <- Get_char();
WHILE (NOT End_of_Line)
DO Next_Char <- Get_char();
IF (Current_Char != Next_char)
THEN Current_Char <- Next_Char;
Next_Char <- Get_char();
Write out Current_Char;
ELSE
WHILE (Current_Char = Next_char)
DO Counter <- Counter + 1;
Current_Char <- Next_Char;
Next_Char <- Get_char();
ENDWHILE;
Write out Counter, Current_Char;
Counter <- 0;
ENDIF;
ENDWHILE;
END.
250. Data Compression
• Or let’s imagine we are sending a list of house prices.
• 350000
• 600000
• 550000
• 2100000
• 3000000
251. Data Compression
• Now let’s use the # to indicate number of zeros:
• 350000
• 600000
• 550000
• 2100000
• 3000000
252. Data Compression
• Now let’s use the # to indicate number of zeros:
• 350000
• 600000
• 550000
• 2100000
• 3000000
• 35#4
• 6#5
• 55#4
• 21#5
• 3#6
272. Modularisation
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
274. Modularisation
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
275. Modularisation
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)
276. Modularisation
• It would be good if there was some way we could wrap
up frequently used commands into a single package, and
instead of having to rewrite the same code over and over
again, we could just call the package name.
• We can call these packages methods or functions
• (or subroutines or procedures)
278. Modularisation
PROGRAM CheckPrime:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
IF (IsPrime = FALSE)
THEN Print “Not Prime”;
ELSE Print “Prime”;
ENDIF;
END.
280. Modularisation
PROGRAM CheckPrime:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
IF (IsPrime = FALSE)
THEN Print “Not Prime”;
ELSE Print “Prime”;
ENDIF;
END.
283. Modularisation
MODULE PrimeChecker:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
RETURN IsPrime;
END.
284. Modularisation
MODULE PrimeChecker:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
RETURN IsPrime;
END.
286. Modularisation
PROGRAM CheckPrime:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
IF (IsPrime = FALSE)
THEN Print “Not Prime”;
ELSE Print “Prime”;
ENDIF;
END.
289. Modularisation
MODULE PrimeChecker:
Read A;
B <- A - 1;
IsPrime <- TRUE;
WHILE (B != 1)
DO IF (A/B gives no remainder)
THEN IsPrime <- FALSE;
ENDIF;
B <- B – 1;
ENDWHILE;
RETURN IsPrime;
END.
290. Modularisation
• Modularisation make life easier for a lot of reasons:
– It easier for someone else to understand how the code works
– It makes team programming a lot easier, different programmers
can work on different methods
– Can improve the quality of the code
– Can reuse the same code over and over again (“don’t reinvent
the wheel”).
291. Modularisation
• If we were writing programs about primes, it would be
useful to have a pre-packaged prime test, e.g.
• If we were writing a program to explore Goldbach's
conjecture, that all even integers are sums of two primes,
if would be useful.
• Also if we were exploring twin primes, which are prime
numbers that has a gap of two, (3, 5), (5, 7), (11, 13), (17,
19), (29, 31), (41, 43), (59, 61), (71, 73), (101, 103), (107,
109), (137, 139), it would be useful.
294. • Why do pilots bother doing pre-flight checks when
the chances are that the plane is working fine?
Question
295. • Software testing is an investigate process to measure the quality of
software.
• Test techniques include, but are not limited to, the process of
executing a program or application with the intent of finding
software bugs.
Software Testing
296. Software Testing
• How is a software system built?
– Customer contacts an I.T. Company and requests that a software
system be created
– The customer works with an analyst to define a design of the
software system
– The design is given to developers to build the software system
– The developed system is given to software testers to check if it is OK
– The system is handed over to the customers
297. • The IBM Automatic Sequence
Controlled Calculator (ASCC), called
the Mark I by Harvard University was
an electro-mechanical computer.
• It was devised by Howard H. Aiken,
built at IBM and shipped to Harvard in
February 1944.
• It began computations for the U.S.
Navy Bureau of Ships in May and was
officially presented to the university
on August 7, 1944.
• It was very reliable, much more so
than early electronic computers.
Harvard Mark I
298. • Howard Hathaway Aiken
• Born March 8, 1900
• Died March 14, 1973
• Born in Hoboken, New Jersey
• He envisioned an electro-
mechanical computing device that
could do much of the tedious work
for him.
• With help from Grace Hopper and
funding from IBM, the machine
was completed in 1944.
Howard H. Aiken
299. • Rear Admiral Grace Murray
Hopper
• Born December 9, 1906
• Died January 1, 1992
• Born in New York City, New York
• Computer pioneer who
developed the first compiler for
a computer programming
language
Grace Hopper
300. • Grace Hopper served at the Bureau of Ships Computation
Project at Harvard University working on the computer
programming staff.
• A moth was found trapped between points at Relay #70, Panel
F, of the IBM Harvard Mark II Aiken Relay Calculator while it
was being tested at Harvard University, 9 September 1945.
The First Bug
301. • The operators affixed the moth to the computer log, with the
entry: "First actual case of bug being found".
• Grace Hopper said that they "debugged" the machine, thus
introducing the term "debugging a computer program".
The First Bug
304. Eras of Testing
Years Era Description
1945-1956 Debugging orientated In this era, there was no clear difference between testing and
debugging.
1957-1978 Demonstration orientated In this era, debugging and testing are distinguished now - in
this period it was shown, that software satisfies the
requirements.
1979-1982 Destruction orientated In this era, the goal was to find errors.
1983-1987 Evaluation orientated In this era, the intention here is that during the software
lifecycle a product evaluation is provided and measuring
quality.
1988- Prevention orientated In the current era, tests are used to demonstrate that
software satisfies its specification, to detect faults and to
prevent faults.
308. • Black box testing treats the software as a "black box"—without any
knowledge of internal implementation.
• Black box testing methods include:
– equivalence partitioning,
– boundary value analysis,
– all-pairs testing,
– fuzz testing,
– model-based testing,
– exploratory testing and
– specification-based testing.
Black Box Testing
309. • White box testing is when the tester has access to the internal
data structures and algorithms including the code that
implement these.
• White box testing methods include:
– API testing (application programming interface) - testing of the
application using public and private APIs
– Code coverage - creating tests to satisfy some criteria of code
coverage (e.g., the test designer can create tests to cause all
statements in the program to be executed at least once)
– Fault injection methods - improving the coverage of a test by
introducing faults to test code paths
– Mutation testing methods
– Static testing - White box testing includes all static testing
White Box Testing
310. • Grey Box Testing involves having knowledge of internal
data structures and algorithms for purposes of
designing the test cases, but testing at the user, or
black-box level.
• The tester is not required to have a full access to the
software's source code.
• Grey box testing may also include reverse engineering
to determine, for instance, boundary values or error
messages.
Grey Box Testing
318. • Program testing and fault detection can be aided significantly by
testing tools and debuggers. Testing/debug tools include features
such as:
– Program monitors, permitting full or partial monitoring of program code
(more on the next slide).
– Formatted dump or symbolic debugging, tools allowing inspection of
program variables on error or at chosen points.
– Automated functional GUI testing tools are used to repeat system-level
tests through the GUI.
– Benchmarks, allowing run-time performance comparisons to be made.
– Performance analysis (or profiling tools) that can help to highlight hot
spots and resource usage.
Testing Tools
319. • Program monitors, permitting full or partial monitoring of
program code including:
– Instruction set simulator, permitting complete instruction level
monitoring and trace facilities
– Program animation, permitting step-by-step execution and
conditional breakpoint at source level or in machine code
– Code coverage reports
Testing Tools
322. Arrays
• Imagine we had to record the age of everyone in the class, we
could do it declaring a variable for each person.
323. Arrays
• Imagine we had to record the age of everyone in the class, we
could do it declaring a variable for each person.
• E.g.
– Integer Age1;
– Integer Age2;
– Integer Age3;
– Integer Age4;
– Integer Age5;
– etc.
324. Arrays
• But if there was a way to collect them all together, and declare
a single special variable for all of them, that would be quicker.
• We can, and the special variable is called an ARRAY.
326. Arrays
• We declare an array as follows:
• Integer Age[40];
• Which means we declare 40 integer variables, all can be
accessed using the Age name.
……..…
327. Arrays
• We declare an array as follows:
• Integer Age[40];
• Which means we declare 40 integer variables, all can be
accessed using the Age name.
0 1 2 3 4 5 6 397 ……..… 38
329. Arrays
44 23 42 33 16 - - 34 8218 ……..… 34
0 1 2 3 4 5 6 7 38 39
• So if I do:
• PRINT Age[0];
• We will get:
• 44
330. Arrays
44 23 42 33 16 - - 34 8218 ……..… 34
0 1 2 3 4 5 6 7 38 39
• So if I do:
• PRINT Age[2];
• We will get:
• 42
331. Arrays
44 23 42 33 16 - - 34 8218 ……..… 34
0 1 2 3 4 5 6 7 38 39
• So if I do:
• PRINT Age[39];
• We will get:
• 82
332. Arrays
44 23 42 33 16 - - 34 8218 ……..… 34
0 1 2 3 4 5 6 7 38 39
• So if I do:
• PRINT Age[40];
• We will get:
• Array Out of Bounds Exception
333. Arrays
44 23 42 33 16 - - 34 8218 ……..… 34
0 1 2 3 4 5 6 7 38 39
• We notice that Age[5] is blank.
• If I want to put a value into it (e.g. 54), I do:
• Age[5] <- 54;
334. Arrays
44 23 42 33 16 54 34 8218 ……..… 34
0 1 2 3 4 5 6 7 38 39
• We notice that Age[5] is blank.
• If I want to put a value into it (e.g. 54), I do:
• Age[5] <- 54;
335. Arrays
• We can think of an array as a series of pigeon-holes:
343. Arrays
• If we want to add up all the values in the array:
344. Arrays
• If we want to add up all the values in the array:
PROGRAM TotalOfArray:
integer Total <- 0;
FOR N IN 0 TO 39
DO Total <- Total + Age[N];
ENDFOR;
END.
346. Arrays
• So the average age is:
PROGRAM AverageOfArray:
integer Total <- 0;
FOR N IN 0 TO 39
DO Total <- Total + Age[N];
ENDFOR;
PRINT Total/40;
END.
347. Arrays
• We can add another variable:
PROGRAM AverageOfArray:
integer Total <- 0;
integer ArraySize <- 40;
FOR N IN 0 TO 39
DO Total <- Total + Age[N];
ENDFOR;
PRINT Total/40;
END.
348. Arrays
• We can add another variable:
PROGRAM AverageOfArray:
integer Total <- 0;
integer ArraySize <- 40;
FOR N IN 0 TO 39
DO Total <- Total + Age[N];
ENDFOR;
PRINT Total/ArraySize;
END.
349. Arrays
• We can add another variable:
PROGRAM AverageOfArray:
integer Total <- 0;
integer ArraySize <- 40;
FOR N IN 0 TO ArraySize-1
DO Total <- Total + Age[N];
ENDFOR;
PRINT Total/ArraySize;
END.
350. • So now if the Array size changes, we just need to change the value
of one variable (ArraySize).
PROGRAM AverageOfArray:
integer Total <- 0;
integer ArraySize <- 40;
FOR N IN 0 TO ArraySize-1
DO Total <- Total + Age[N];
ENDFOR;
PRINT Total/ArraySize;
END.
Arrays
352. Arrays
• We can also have an array of real numbers:
22.00
0
65.50
1
-2.20
2
78.80 54.00 -3.33 0.00 47.65
3 4 5 6 7
353. • What if we wanted to check who has a balance less than zero :
PROGRAM LessThanZeroBalance:
integer ArraySize <- 8;
FOR N IN 0 TO ArraySize-1
DO IF BankBalance[N] < 0
THEN PRINT “User” N “is in debt”;
ENDIF;
ENDFOR;
END.
Arrays
355. Arrays
• We can also have an array of characters:
G A T T C C A AG ……..… A
0 1 2 3 4 5 6 7 38 39
356. • What if we wanted to count all the ‘G’ in the Gene Array:
Arrays
G A T T C C A AG ……..… A
0 1 2 3 4 5 6 7 38 39
357. • What if we wanted to count all the ‘G’ in the Gene Array:
PROGRAM AverageOfArray:
integer ArraySize <- 40;
integer G-Count <- 0;
FOR N IN 0 TO ArraySize-1
DO IF Gene[N] = ‘G’
THEN G-Count <- G-Count + 1;
ENDIF;
ENDFOR;
PRINT “The total G count is:” G-Count;
END.
Arrays
358. • What if we wanted to count all the ‘A’ in the Gene Array:
PROGRAM AverageOfArray:
integer ArraySize <- 40;
integer A-Count <- 0;
FOR N IN 0 TO ArraySize-1
DO IF Gene[N] = ‘A’
THEN A-Count <- A-Count + 1;
ENDIF;
ENDFOR;
PRINT “The total A count is:” A-Count;
END.
Arrays
368. Google Search Algorithm
• First Draft:
PROGRAM GoogleCollect:
NextLink <- random website;
WHILE (NextLink != NULL)
DO IF (No copy of this page in google collection)
THEN copy this page into google collection;
ENDIF;
NextLink <- Next link on this page;
ENDWHILE;
END.
369. Google Search Algorithm
• First Draft:
PROGRAM GoogleSearch:
READ SearchString;
Get First Webpage from collection;
WHILE (Webpages Left to Search)
DO IF (SearchString IN Current-Web-Page)
THEN Put this page on the list;
ENDIF;
Get Next Webpage;
ENDWHILE;
Order the list according to PageRank;
END.
419. Searching: Sequential Search
• This is a SEQUENTIAL SEARCH.
• If the array is 40 characters long, it will take 40 checks to
complete. If the array is 1000 characters long, it will take 1000
checks to complete.
420. • Here’s how we could do it:
PROGRAM SequentialSearch:
integer SearchValue <- 18;
integer ArraySize <- 40;
FOR N IN 0 TO ArraySize-1
DO IF Age[N] = SearchValue
THEN PRINT “User “ N “is 18”;
ENDIF;
ENDFOR;
END.
Searching: Sequential Search
424. Searching: Binary Search
• If the data is sorted, we can do a BINARY SEARCH
• This means we jump to the middle of the array, if the value
being searched for is less than the middle value, all we have to
do is search the first half of that array.
425. Searching: Binary Search
• If the data is sorted, we can do a BINARY SEARCH
• This means we jump to the middle of the array, if the value
being searched for is less than the middle value, all we have to
do is search the first half of that array.
• We search the first half of the array in the same way, jumping
to the middle of it, and repeat this.
436. Searching: Binary Search
• The BINARY SEARCH just takes five checks to find the right
value in an array of 40 elements. For an array of 1000 elements
it will take 11 checks.
• This is much faster than if we searched through all the values.
437. • If the data is sorted, we can do a BINARY SEARCH
PROGRAM BinarySearch:
integer First <- 0;
integer Last <- 40;
boolean IsFound <- FALSE;
WHILE First <= Last AND IsFound = FALSE
DO Index = (First + Last)/2;
IF Age[Index] = SearchValue
THEN IsFound <- TRUE;
ELSE IF Age[Index] > SearchValue
THEN Last <- Index-1;
ELSE First <- Index+1;
ENDIF;
ENDIF;
ENDWHILE;
END.
Searching: Binary Search
440. Minimum Value in Array
• So let’s say we want to express the following algorithm:
– Find the minimum value in an array
441. • Here’s how we could do it:
PROGRAM MinimumValue:
integer ArraySize <- 8;
MinValSoFar <- Age[0];
FOR N IN 1 TO ArraySize-1
DO IF MinValSoFar > Age[N]
THEN MinValSoFar <- Age[N];
ENDIF;
ENDFOR;
PRINT MinValSoFar;
END.
Minimum Value in Array
442. Maximum Value in Array
• So let’s say we want to express the following algorithm:
– Find the maximum value in an array
443. • Here’s how we could do it:
PROGRAM MaximumValue:
integer ArraySize <- 8;
MaxValSoFar <- Age[0];
FOR N IN 1 TO ArraySize-1
DO IF MaxValSoFar < Age[N]
THEN MaxValSoFar <- Age[N];
ENDIF;
ENDFOR;
PRINT MaxValSoFar;
END.
Maximum Value in Array
444. Average Value in Array
• So let’s say we want to express the following algorithm:
– Find the average value of an array
445. • Here’s how we could do it:
PROGRAM AverageValue:
integer ArraySize <- 8;
Integer Total <- 0;
FOR N IN 1 TO ArraySize-1
DO Total <- Total + Age[N];
ENDFOR;
PRINT Total/ArraySize;
END.
Average Value in Array
446. Standard Deviation of an Array
• So let’s say we want to express the following algorithm:
– Find the standard deviation of an array
447. Standard Deviation of an Array
• So let’s say we want to express the following algorithm:
– Find the standard deviation of an array
448. • First Draft
PROGRAM StandardDeviationValue:
integer ArraySize <- 8;
GET AVERAGE OF ARRAY;
TotalSDNum <- 0;
FOR N IN 0 TO ArraySize-1
DO SDNum <-(Age[N]-ArrayAvg)*(Age[N]-ArrayAvg)
TotalSDNum <- TotalSDNum + SDNum;
ENDFOR;
Print SquareRoot(TotalSDNum/ArraySize-1);
END.
Standard Deviation of an Array
449. • Here’s the final version:
PROGRAM StandardDeviationValue:
integer ArraySize <- 8;
Integer TotalAvg <- 0;
FOR N IN 1 TO ArraySize-1
DO TotalAvg <- TotalAvg + Age[N];
ENDFOR;
AverageValue <- TotalAvg/ArraySize;
TotalSDNum <- 0;
FOR N IN 0 TO ArraySize-1
DO SDNum <-(Age[N]-AverageValue)*(Age[N]- AverageValue)
TotalSDNum <- TotalSDNum + SDNum;
ENDFOR;
Print SquareRoot(TotalSDNum/ArraySize-1);
END.
Standard Deviation of an Array
454. Sorting
44 23 42 33 16 54 34 18
0 1 2 3 4 5 6 7
• How do we sort the data, in other words, get it into this order:
455. Sorting
44 23 42 33 16 54 34 18
0 1 2 3 4 5 6 7
• How do we sort the data, in other words, get it into this order:
16 18 23 33 34 42 44 54
0 1 2 3 4 5 6 7
456. Sorting
• As humans, we can sort the array just by inspection (just be
looking at it), but if the array was 100,000 elements long it
would be more of a challenge for us.
458. Sorting: Bubble Sort
• The simplest algorithm for sort an array is called BUBBLE SORT.
• It works as follows:
459. Sorting: Bubble Sort
• The simplest algorithm for sort an array is called BUBBLE SORT.
• It works as follows for an array of size N:
– Look at the first and second element
• Are they in order?
• If so, do nothing
• If not, swap them around
– Look at the second and third element
• Do the same
– Keep doing this until you get to the end of the array
– Go back to the start again keep doing this whole process for N times.
460. • Lets look at the swapping bit
– if I wanted to swap two values, the following won’t work:
Age[0] <- Age[1];
Age[1] <- Age[0];
– Why not?
Sorting: Bubble Sort
461. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
462. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
23
463. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
2323
464. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
2323
23
465. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
2323
2323
466. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
2323
2323
467. • Lets assume Age[0]=44, and Age[1]=23, if we do the following:
Age[0] <- Age[1];
Age[1] <- Age[0];
– What happens is:
Age[0] <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
2323
2323
468. • We need an extra variable to make this work:
Sorting: Bubble Sort
469. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Sorting: Bubble Sort
470. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Sorting: Bubble Sort
471. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Sorting: Bubble Sort
472. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
473. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
23
474. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
475. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
44
476. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
4444
477. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
4444
23
478. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
4444
2323
479. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
4444
2323
480. • We need an extra variable to make this work:
• Lets call it Temp_Value.
Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
Sorting: Bubble Sort
2323
4444
2323
481. • Let’s wrap an IF statement around this:
IF (Age[1] < Age[0])
THEN Temp_Value <- Age[1];
Age[1] <- Age[0];
Age[0] <- Temp_Value;
ENDIF;
Sorting: Bubble Sort
482. • And in general:
IF (Age[N+1] < Age[N])
THEN Temp_Value <- Age[N+1];
Age[N+1] <- Age[N];
Age[N] <- Temp_Value;
ENDIF;
Sorting: Bubble Sort
483. • Let’s replace “N” with “Index”
IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
Sorting: Bubble Sort
484. • To get from one end of the array to another:
FOR Index IN 0 TO N-2
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
ENDFOR;
Sorting: Bubble Sort
485. • Does this mean we have the array sorted?
Sorting: Bubble Sort
486. • Does this mean we have the array sorted?
• No
Sorting: Bubble Sort
503. Sorting: Bubble Sort
23 42 33 16 44 34 18 54
0 1 2 3 4 5 6 7
• So what happened?
• We have moved the largest value (54) into the correct position.
519. • So what happened?
• We have moved the second largest value (44) into the correct
position.
Sorting: Bubble Sort
23 42 16 33 34 18 44 54
0 1 2 3 4 5 6 7
535. Sorting: Bubble Sort
23 16 33 34 18 42 44 54
0 1 2 3 4 5 6 7
• So what happened?
• We have moved the third largest value (42) into the correct
position.
551. Sorting: Bubble Sort
16 23 33 18 34 42 44 54
0 1 2 3 4 5 6 7
• So what happened?
• We have moved the fourth largest value (34) into the correct
position.
566. Sorting: Bubble Sort
16 23 18 33 34 42 44 54
0 1 2 3 4 5 6 7
• So what happened?
• We have moved the fifth largest value (33) into the correct
position.
582. Sorting: Bubble Sort
16 18 23 33 34 42 44 54
0 1 2 3 4 5 6 7
• So what happened?
• We have moved the sixth largest value (23) into the correct
position.
588. • So we need two loops:
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO N-2
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
ENDFOR;
ENDFOR;
Sorting: Bubble Sort
589. PROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO N-2
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
ENDFOR;
ENDFOR;
END.
Sorting: Bubble Sort
594. PROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO N-2
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
ENDFOR;
ENDFOR;
END.
Sorting: Bubble Sort
595. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
596. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
597. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
598. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
599. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
600. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
601. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
602. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
603. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
604. Sorting: Bubble Sort
• The bubble sort pushes the largest values up to the top of the
array.
605. Sorting: Bubble Sort
• So each time around the loop the amount of the array that is
sorted is increased, and we don’t have to check for swaps in
the locations that have already been sorted.
• So we reduce the checking of swaps by one each time we do a
pass of the array.
606. PROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
ReducingIndex <- N-2;
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO ReducingIndex
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
ENDFOR;
ReducingIndex <- ReducingIndex – 1;
ENDFOR;
END.
Sorting: Bubble Sort
607. PROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
ReducingIndex <- N-2;
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO ReducingIndex
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
ENDIF;
ENDFOR;
ReducingIndex <- ReducingIndex – 1;
ENDFOR;
END.
Sorting: Bubble Sort
608. Sorting: Bubble Sort
• Also, what if the data is already sorted?
• We should check if the program has done no swaps in one
pass, and if t doesn’t that means the data is sorted.
• So even if the data started unsorted, as soon as the data gets
sorted we want to exit the program.
609. Sorting: Bubble SortPROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
ReducingIndex <- N-2;
DidSwap <- FALSE;
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO ReducingIndex
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
DidSwap <- TRUE;
ENDIF;
ENDFOR;
ReducingIndex <- ReducingIndex – 1;
IF (DidSwap = FALSE)
THEN EXIT;
ENDIF;
ENDFOR;
END.
610. PROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
ReducingIndex <- N-2;
DidSwap <- FALSE;
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO ReducingIndex
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
DidSwap <- TRUE;
ENDIF;
ENDFOR;
ReducingIndex <- ReducingIndex – 1;
IF (DidSwap = FALSE)
THEN EXIT;
ENDIF;
ENDFOR;
END.
Sorting: Bubble Sort
611. Sorting: Bubble Sort
• The Swap function is very useful so we should have that as a
method as follows:
613. PROGRAM BubbleSort:
Integer Age[8] <- {44,23,42,33,16,54,34,18};
ReducingIndex <- N-2;
DidSwap <- FALSE;
FOR Outer-Index IN 0 TO N-1
DO FOR Index IN 0 TO ReducingIndex
DO IF (Age[Index+1] < Age[Index])
THEN Temp_Value <- Age[Index+1];
Age[Index+1] <- Age[Index];
Age[Index] <- Temp_Value;
DidSwap <- TRUE;
ENDIF;
ENDFOR;
ReducingIndex <- ReducingIndex – 1;
IF (DidSwap = FALSE)
THEN EXIT;
ENDIF;
ENDFOR;
END.
Sorting: Bubble Sort