You are on page 1of 276

4.

Computational thinking, problem-solving and


programming
4. Computational thinking, problem-solving and programming 2 / 192

General Principles

Thinking Procedurally
Thinking Logically
Thinking Ahead
Thinking Concurrently
Thinking Abstractly
4. Computational thinking, problem-solving and programming 3 / 192

The concept of a problem

Problem (By Cambridge Dictionary)


A problem is a situation that needs attention and needs to be dealt with
or solved.
Whenever we have to deal with a problem, we have to take on or more
decisions.
Decision making process:
Identification
Development
Selection
Implementation
The decision making process will solve most problems, but it does not
guarantee a solution of all problems.
The decision making process is not linear. Sometimes it is necessary to
return to a previous stage.
4. Computational thinking, problem-solving and programming 4 / 192

Decision making process

Identification
Identify the problem
Understand the problem
Formulate the problem

Development
Explore various alternatives

Selection
Choose the best alternative

Implementation
Implement the selected solution
4. Computational thinking, problem-solving and programming 5 / 192

Identify the procedure appropriate to solving a problem

Generally speaking, all problems begin with an idea.


Finding the connection between this information and the solution lies at
the heart of problem solving.
To do this, several strategies could be utilised. For example:
Asking questions
Looking for Familiar Things
Divide and Conquer
...
4. Computational thinking, problem-solving and programming 6 / 192

Appropriate procedure for solving a problem

When a particular problem has to be solved, an effective method or


procedure should be identified.
This procedure reduces the solution to a series of simple steps.
These steps have to be followed in the correct order to obtain the desired
output.
Question
A new student in our school wants to go from the IB DP building to the
dining room. Define the steps he has to follow and identify the overall
procedure for problem solving.
4. Computational thinking, problem-solving and programming 7 / 192

Identify the procedure appropriate to solving a problem

Question
Identify the procedure appropriate to solving the following problems:
Bake a cake.
Go to the dining room.
Clean up the classroom tables.
4. Computational thinking, problem-solving and programming 8 / 192

Order of activities

We constantly break up a large problem into smaller units that we can


handle.
The task of cleaning the house or apartment may seem overwhelming.
The task composed of cleaning the living room, the dining room, the
kitchen, the bedrooms, and the bathroom seems more manageable.
This principle is especially relevant to computing.
Upon looking at a certain order of activities, we should state the optimal
way to proceed. Our evaluation could even be that
“no, that’s not a very good way to proceed”
and then we should propose a more optimal order.
4. Computational thinking, problem-solving and programming 9 / 192

Orders of activities and required outcome

A company wishes to develop a new information system.


The analysis phase will be the one that the company should
complete before proceeding to the next stages of the project.
If the company tries to implement the new system without first
analysing the problem, then a total waste of money, effort and
resources will almost certainly occur.
4. Computational thinking, problem-solving and programming 10 / 192

Evaluate the order in which activities are undertaken

Question 1
For the following problems present an order in which activities could be
undertaken that will lead to the desired result and an order in which
activities could be undertaken that will not lead to the desired result.
Baking a cake
Go to the dining room
Clean up the classroom desks

Question 2
Explain the importance of the order in which activities are performed.
4. Computational thinking, problem-solving and programming 11 / 192

Do not reinvent the wheel

If a solution exists, use it. If you have solved the same or a similar
problem before, just repeat the successful solution.
We usually do not consciously think, “I have seen this before, and I
know what to do” - we just do it.
Humans are good at recognising similar situations.
We do not have to learn how to go to the store and buy milk, then
to buy eggs, then to buy candy. We know that going to the store is
always the same and only what we buy is different.
4. Computational thinking, problem-solving and programming 12 / 192

Do not reinvent the wheel

Recognising familiar situations is particularly useful in computing.


In computing, you see certain problems again and again in different
guises.
A good programmer sees a task, or perhaps part of a task (a
subtask), that has been solved before and plugs in the solution.
For example, finding daily high and low temperatures in a list of
temperatures is exactly the same problem as finding the highest and
lowest grades in a list of test scores. You want to the find the largest
and smallest values in a set of numbers.
4. Computational thinking, problem-solving and programming 13 / 192

Confronting a complex problem

A good approach for confronting a complex problem is to develop a


method of breaking up the problem into smaller sub-problems.
This method is very effective and efficient because it is much easier
to attack a number of sub-problems instead of a big complex
problem.
The resulting sub-problems can be further divided into smaller
sub-problems, until they can finally be dealt individually.
This strategy is often called top-down design or stepwise refinement.
4. Computational thinking, problem-solving and programming 14 / 192

Algorithms and Their Properties

Algorithm
An algorithm is a series of unambiguous instructions designed in order to
solve a problem and achieve a certain goal in a finite number of steps.

An algorithm usually (possesses) the following properties:


Finiteness: an algorithm must always terminate after a finite number
of steps
Definiteness: each step must be precisely defined, the actions to be
carried out must be rigorously and unambiguously
specified for each case
Input: quantities which are given initially before the algorithm
begins. These inputs are taken from specified sets of
objects
Output: quantities which are produced (usually printed) during the
execution of the algorithm
4. Computational thinking, problem-solving and programming 15 / 192

More Properties of Algorithms


Correctness: refers to the extent to which the algorithm satisfies its
specification, is free from faults, and fulfils all objectives
set during the design and implementation phase.
Complexity: refers to the amount of the computer resources required to
perform its functions. Minimising the use of various
resources such as CPU time and memory is very important.
Reliability: refers to the capability of the algorithm to maintain a
predefined level of performance and perform all required
functions under stated conditions, having a long mean
time between failures.
Scalability: refers to the effort required to modify the algorithm for
other purposes than those for which it was initially
developed.
Efficiency: this is one of the most desired properties of algorithms.
The developer has to make sure that the algorithm
completes the desired task using the least possible
resources (usually this means as fast as possible). An
efficient algorithm has low complexity and an inefficient
algorithm has high complexity.
4. Computational thinking, problem-solving and programming 16 / 192

Examples

An algorithm that sorts a list of integers by checking every possible


combination of them is inefficient and has high complexity.
An algorithm that translates Greek text to English text and highly
depends on the Greek grammar is not scalable.
An algorithm that claims to sort any list of integers but does not
work for negative integers is not correct.
...
4. Computational thinking, problem-solving and programming 17 / 192

Representation of Algorithms

An algorithm can be represented using:


1 natural language (Greek, English, Spanish, etc.),
2 flow charts,
3 pseudocode or
4 a programming language.
For now we will focus on the 3rd approch. No matter how informal,
writing algorithms in pseudocode requires the definition of a formal
language.
The language we will use, is called IB pseudocode.
4. Computational thinking, problem-solving and programming 18 / 192

IB Pseudocode

IB pseudocode is a (relatively) formal language that is used in the IB


examination in order to represent algorithms. It is much stricter than any
physical language (e.g. Greek or english). However it is to informal to be
considered a serious programming language.
An interpreter for this language (i.e. a software application where one can
execute programs in IB pseudocode) can be found in the following url

http://ibcomp.fis.edu/pseudocode/pcode.html.
4. Computational thinking, problem-solving and programming 19 / 192

Key features of IB pseudocode


Keywords: words like input, output, loop, if, then, else, . . . These
words cannot be used as identifiers and should always be written as
they are. In the lecture slides they will be represented with blue and
they will always be lowercase.
Identifiers: names for variables (or sub-procedures). In the lecture
slides they will be represented with black. The will always be
uppercase.
Strings: everything that you put between ”. For example ”Hello
World!”, ”My computer science instructor awesome!”. In the lecture
slides they will be represented with purple.
Comments: Everything that you write from the symbols // until the
end of line. They will be represented in light green.

Identify the strings, keywords, identifiers and comments:


 
1 A = input ( " Give a number " ) // read the first number
2 B = input ( " Give another number " ) // read the second number
3 D = A - B // compute the difference of A and B
4 output " The difference of the given numbers is " , D
 
4. Computational thinking, problem-solving and programming 20 / 192

Comments

Comments obey no rules and can be anything. Their purpose is to help


others (and perhaps even you after some time) to understand your code.
 
1 R = input ( " Give the radius of the circle " )
2 D = 2 * 3.14159 * R // compute the perimeter of the circle
3 output " The perimeter of the circle is " , R
 
4. Computational thinking, problem-solving and programming 21 / 192

Arithmetical Expressions

Arithmetical expressions in IB pseudocode follow similar notation as in


mathematics
Mathematics IB pseudocode
2
x +1 x^2 + 1
y
2x + z 2 * x + y/z
1
xy + z − w x * y +z - 1/w
4. Computational thinking, problem-solving and programming 22 / 192

Examples

Write an algorithm that takes as input two numbers and adds them.
4. Computational thinking, problem-solving and programming 22 / 192

Examples

Write an algorithm that takes as input two numbers and adds them.
 
1 A = input ( " Give the first number " )
2 B = input ( " Give the second number " )
3 S = A+B
4 output " The sum is " , S
 
Write an algorithm that takes as input the initial value of a product and
the value of VAT and computes the final value of the product
4. Computational thinking, problem-solving and programming 22 / 192

Examples

Write an algorithm that takes as input two numbers and adds them.
 
1 A = input ( " Give the first number " )
2 B = input ( " Give the second number " )
3 S = A+B
4 output " The sum is " , S
 
Write an algorithm that takes as input the initial value of a product and
the value of VAT and computes the final value of the product
 
1 I = input ( " Give a the initial value of the product " )
2 V = input ( " Give the VAT " )
3 F = I + V * I /100
4 output " The final value is " , F
 
4. Computational thinking, problem-solving and programming 23 / 192

Variables

CAUTION!!!!!
Variables in computer science do not behave as variables in mathematics.

A variable is a name given to a memory location.


The contents of the memory location that corresponds to this
variable can be changed with the assignment command.
If X is a variable (i.e. a name for a memory location) then an
assignment command looks like

X =3
4. Computational thinking, problem-solving and programming 24 / 192

The Assignment Statement


After every assignment command the
old value of the variable is discarded
and the variable (that is the memory
location) has now a new value.
That is after the following code

X =5
X = 11
X = 17

the variable X has the value 17.


The old values of X , that is 5 and 11 are lost and cannot be
retrieved.
A variable can be understood as a bucket that is emptied exactly
before each assignment statement. After the assignment statement
the variable has the value that was on the right of the assignment
statement.
4. Computational thinking, problem-solving and programming 25 / 192

Assignment of Variables

The expression at the right of an assignment statement may contain


other variables too.
What will the following pieces of code print?
 
1 A = 4
2 B = 8
3 C = A * B - 12
4 D = C * C
5 output D
 
 
1 X = 3
2 Y = -4
3 Z = X + Y - 20
4 output Z
 
4. Computational thinking, problem-solving and programming 26 / 192

Assignment of variables

The expression at the right of an assignment statement is evaluated right


before the assignment.
This is particularly important for assignments where the same variable
appears on the right and on the left of =.
4. Computational thinking, problem-solving and programming 26 / 192

Assignment of variables

The expression at the right of an assignment statement is evaluated right


before the assignment.
This is particularly important for assignments where the same variable
appears on the right and on the left of =.
What will the following pieces of code print?
 
1 X = 3
2 X = X + 8
3 output X
 
 
1 A = 3
2 A = A * A * 8
3 output A
 
4. Computational thinking, problem-solving and programming 26 / 192

Assignment of variables

The expression at the right of an assignment statement is evaluated right


before the assignment.
This is particularly important for assignments where the same variable
appears on the right and on the left of =.
What will the following pieces of code print?
 
1 X = 3
2 X = X + 8
3 output X
 
 
1 A = 3
2 A = A * A * 8
3 output A
 
Now the difference with Mathematics is clear. In mathematics one can
never write the following:
X = X + 3.
4. Computational thinking, problem-solving and programming 27 / 192

Convert Sentences into Assignments

The value of X is increased by 2


The value of X is doubled
The value of X is increased by Y and Z
The value of X is decreased by 2
The value of X is divided by 3
4. Computational thinking, problem-solving and programming 27 / 192

Convert Sentences into Assignments

The value of X is increased by 2 X =X +2


The value of X is doubled
The value of X is increased by Y and Z
The value of X is decreased by 2
The value of X is divided by 3
4. Computational thinking, problem-solving and programming 27 / 192

Convert Sentences into Assignments

The value of X is increased by 2 X =X +2


The value of X is doubled X =2∗X
The value of X is increased by Y and Z
The value of X is decreased by 2
The value of X is divided by 3
4. Computational thinking, problem-solving and programming 27 / 192

Convert Sentences into Assignments

The value of X is increased by 2 X =X +2


The value of X is doubled X =2∗X
The value of X is increased by Y and Z X =X +Y +Z
The value of X is decreased by 2
The value of X is divided by 3
4. Computational thinking, problem-solving and programming 27 / 192

Convert Sentences into Assignments

The value of X is increased by 2 X =X +2


The value of X is doubled X =2∗X
The value of X is increased by Y and Z X =X +Y +Z
The value of X is decreased by 2 X =X −2
The value of X is divided by 3
4. Computational thinking, problem-solving and programming 27 / 192

Convert Sentences into Assignments

The value of X is increased by 2 X =X +2


The value of X is doubled X =2∗X
The value of X is increased by Y and Z X =X +Y +Z
The value of X is decreased by 2 X =X −2
The value of X is divided by 3 X = X /3
4. Computational thinking, problem-solving and programming 28 / 192

Examples

What value should you give for X such that 5 is printed?


 
1 input X
2 X = X - 8
3 output X
 
4. Computational thinking, problem-solving and programming 28 / 192

Examples

What value should you give for X such that 5 is printed?


 
1 input X
2 X = X - 8
3 output X
 
What values can you give to X and Y such that 10 is printed?
 
1 input X
2 input Y
3 Y = Y - 5
4 X = X + Y
5 output X
 
4. Computational thinking, problem-solving and programming 29 / 192

Allowed Notation in IB Pseudocode

Symbol Functionality Examples


= equality testing X = 5, X = K + Y
and assignment
>, >=, comparisons
<=, 6=
AND logical conjunction if X < 7 AND Y > 2
then . . .
OR logical disjunction if X < 7 OR Y > 2
then . . .
NOT logical negation if NOT X = 7 then . . .
mod modulo 15 mod 7 = 1
div integer part of quo- 15 div 7 = 2
tient
input input of the algorithm input a
output output of the output ”Hello world”
algorithm
4. Computational thinking, problem-solving and programming 30 / 192

Differences between interpreter and approved notation

Interpreter of IB Pseudocode

http://ibcomp.fis.edu/pseudocode/pcode.html

Functionality Interpreter Approved Notation


Not equal != , <> 6 =
input input a input (a,b)
input b
output output a output (a,b)
output b
mod 5%3 5 mod 3
div div(5,3) 5 div 3
The above are small differences. It is OK in the exam if you slightly
abuse notation.
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3
3 mod 7
5 div 2
2 div 5
15 + 9 div 2
3/2
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3 1
3 mod 7
5 div 2
2 div 5
15 + 9 div 2
3/2
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3 1
3 mod 7 3
5 div 2
2 div 5
15 + 9 div 2
3/2
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3 1
3 mod 7 3
5 div 2 2
2 div 5
15 + 9 div 2
3/2
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3 1
3 mod 7 3
5 div 2 2
2 div 5 0
15 + 9 div 2
3/2
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3 1
3 mod 7 3
5 div 2 2
2 div 5 0
15 + 9 div 2 19
3/2
4. Computational thinking, problem-solving and programming 31 / 192

Determine the values of the expressions

7 mod 3 1
3 mod 7 3
5 div 2 2
2 div 5 0
15 + 9 div 2 19
3/2 1.5
4. Computational thinking, problem-solving and programming 32 / 192

Examples

What will the following pieces of code print?


 
1 X = 3
2 X = X mod 8
3 output X
 
 
1 A = 16
2 A = A div 8
3 A = A * A
4 output A
 
4. Computational thinking, problem-solving and programming 33 / 192

Examples

What value could you give to X such that 3 is printed? (actually there
are infinite values . . . )
 
1 input X
2 X = X + 2
3 Y = X mod 4
4 output Y
 
What value could you give to A such that 2 is printed? (there are 3
positive integer values. Try and find them)
 
1 input A
2 A = A - 3
3 B = A div 3
4 output B
 
4. Computational thinking, problem-solving and programming 34 / 192

Conditions

In programming it is very often the case, that we have to check whether


a condition holds and then proceed accordingly.

Remember the analogy with real life:


If it is red I wait, else (i.e. if it is green) I cross the road.
4. Computational thinking, problem-solving and programming 35 / 192

The if-then-else command

Write a program that takes two numbers as input, A and B and print the
smallest of them. (If the numbers are equal the smallest is any of the
numbers).
4. Computational thinking, problem-solving and programming 35 / 192

The if-then-else command

Write a program that takes two numbers as input, A and B and print the
smallest of them. (If the numbers are equal the smallest is any of the
numbers).
 
1 input A
2 input B
3 if A < B then
4 output A
5 else
6 output B
7 end if
 
4. Computational thinking, problem-solving and programming 36 / 192

Example

Write a program that takes three numbers as input:


V : the original value of the product
D: the value of the discount as a percentage
A: the amount that the customer has available
If the value after the discount is more than A then the program prints the
message “You cannot buy it”. Otherwise it prints the message you can
buy it.
4. Computational thinking, problem-solving and programming 36 / 192

Example

Write a program that takes three numbers as input:


V : the original value of the product
D: the value of the discount as a percentage
A: the amount that the customer has available
If the value after the discount is more than A then the program prints the
message “You cannot buy it”. Otherwise it prints the message you can
buy it.
 
1 input V
2 input D
3 input A
4 if A >= V - V * D then
5 output " You can but it "
6 else
7 output " You cannot but it "
8 end if
 
4. Computational thinking, problem-solving and programming 37 / 192

Example

Write a program that takes a number X as input and does the following.
If X ∈ [0, 5] it prints the message “Valid Number”
If X ∈
/ [0, 5] it prints the message “Not Valid Number”
4. Computational thinking, problem-solving and programming 37 / 192

Example

Write a program that takes a number X as input and does the following.
If X ∈ [0, 5] it prints the message “Valid Number”
If X ∈
/ [0, 5] it prints the message “Not Valid Number”
 
1 input X
2 if 0 <= X AND X <=5 then
3 output " Valid Number "
4 else
5 output " Not Valid Number "
6 end if
 
4. Computational thinking, problem-solving and programming 38 / 192

Example

Write a program that takes a number X as input and does the following.
If X is a multiple of 5 it prints the message “Valid Number”
If X is not a multiple of 5 it prints the message “Not Valid Number”
4. Computational thinking, problem-solving and programming 38 / 192

Example

Write a program that takes a number X as input and does the following.
If X is a multiple of 5 it prints the message “Valid Number”
If X is not a multiple of 5 it prints the message “Not Valid Number”
 
1 input X
2 if X mod 5 = 0 then
3 output " valid number "
4 else
5 output " Not valid number "
6 end if
 
4. Computational thinking, problem-solving and programming 39 / 192

Example

Write a program that takes a number X as input and does the following.
If X is a multiple of 5 and a multiple of 3 it prints the message
“Valid Number”
If X is not a multiple of 5 or not a multiple of 3 it prints the
message “Not Valid Number”
4. Computational thinking, problem-solving and programming 39 / 192

Example

Write a program that takes a number X as input and does the following.
If X is a multiple of 5 and a multiple of 3 it prints the message
“Valid Number”
If X is not a multiple of 5 or not a multiple of 3 it prints the
message “Not Valid Number”
 
1 input X
2 if X mod 15 = 0 then
3 output " valid number "
4 else
5 output " not valid number "
6 end if
 
4. Computational thinking, problem-solving and programming 40 / 192

Example

The if-then-else command can be used without the else part. In this case,
if the condition is true it executes the code in the if part. If the condition
is false nothing happens.
4. Computational thinking, problem-solving and programming 40 / 192

Example

The if-then-else command can be used without the else part. In this case,
if the condition is true it executes the code in the if part. If the condition
is false nothing happens.
Write an algorithm in IB Pseudocode that takes as input the grades of a
student in Mathematics, Physics and Computer Science and prints the
average. If the average is at least 4 it prints “You have passed”.
4. Computational thinking, problem-solving and programming 40 / 192

Example

The if-then-else command can be used without the else part. In this case,
if the condition is true it executes the code in the if part. If the condition
is false nothing happens.
Write an algorithm in IB Pseudocode that takes as input the grades of a
student in Mathematics, Physics and Computer Science and prints the
average. If the average is at least 4 it prints “You have passed”.
 
1 input A
2 input B
3 input C
4 D = ( A + B + C ) /3
5 output D
6 if D >= 4 then
7 output " You have passed "
8 end if
 
4. Computational thinking, problem-solving and programming 41 / 192

Natural Language VS. Logical Expression

In programming it is often the case that you have to convert natural


language sentences to logical expressions.
Natural Language Logical Expression
X is a multiple of 5

X is greater than the sum of Y


and Z
X is a multiple of 3 and not a
multiple of 7

at least one of X and Y is equal


to 0
the numbers A and B have differ-
ent sign (assuming that A, B 6=
0)
4. Computational thinking, problem-solving and programming 41 / 192

Natural Language VS. Logical Expression

In programming it is often the case that you have to convert natural


language sentences to logical expressions.
Natural Language Logical Expression
X is a multiple of 5
X mod 5 = 0
X is greater than the sum of Y
and Z
X is a multiple of 3 and not a
multiple of 7

at least one of X and Y is equal


to 0
the numbers A and B have differ-
ent sign (assuming that A, B 6=
0)
4. Computational thinking, problem-solving and programming 41 / 192

Natural Language VS. Logical Expression

In programming it is often the case that you have to convert natural


language sentences to logical expressions.
Natural Language Logical Expression
X is a multiple of 5
X mod 5 = 0
X is greater than the sum of Y
and Z X >Y +Z
X is a multiple of 3 and not a
multiple of 7

at least one of X and Y is equal


to 0
the numbers A and B have differ-
ent sign (assuming that A, B 6=
0)
4. Computational thinking, problem-solving and programming 41 / 192

Natural Language VS. Logical Expression

In programming it is often the case that you have to convert natural


language sentences to logical expressions.
Natural Language Logical Expression
X is a multiple of 5
X mod 5 = 0
X is greater than the sum of Y
and Z X >Y +Z
X is a multiple of 3 and not a
multiple of 7 X mod 3 = 0 AND
X mod 7 > 0
at least one of X and Y is equal
to 0
the numbers A and B have differ-
ent sign (assuming that A, B 6=
0)
4. Computational thinking, problem-solving and programming 41 / 192

Natural Language VS. Logical Expression

In programming it is often the case that you have to convert natural


language sentences to logical expressions.
Natural Language Logical Expression
X is a multiple of 5
X mod 5 = 0
X is greater than the sum of Y
and Z X >Y +Z
X is a multiple of 3 and not a
multiple of 7 X mod 3 = 0 AND
X mod 7 > 0
at least one of X and Y is equal
to 0 X ∗Y =0
the numbers A and B have differ-
ent sign (assuming that A, B 6=
0)
4. Computational thinking, problem-solving and programming 41 / 192

Natural Language VS. Logical Expression

In programming it is often the case that you have to convert natural


language sentences to logical expressions.
Natural Language Logical Expression
X is a multiple of 5
X mod 5 = 0
X is greater than the sum of Y
and Z X >Y +Z
X is a multiple of 3 and not a
multiple of 7 X mod 3 = 0 AND
X mod 7 > 0
at least one of X and Y is equal
to 0 X ∗Y =0
the numbers A and B have differ-
ent sign (assuming that A, B 6= A∗B <0
0)
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0
3 mod 7 = 7
25 mod 26 = 25
25 div 26 = 0
5 div 4 = 2
5678 mod 26 = 27
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7
25 mod 26 = 25
25 div 26 = 0
5 div 4 = 2
5678 mod 26 = 27
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25
25 div 26 = 0
5 div 4 = 2
5678 mod 26 = 27
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0
5 div 4 = 2
5678 mod 26 = 27
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2
5678 mod 26 = 27
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27 False
345 div 456 = 34
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27 False
345 div 456 = 34 False
5247 div 1 = 524
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27 False
345 div 456 = 34 False
5247 div 1 = 524 False
1234567 mod 10 = 7
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27 False
345 div 456 = 34 False
5247 div 1 = 524 False
1234567 mod 10 = 7 True
4567 mod 100 = 67
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27 False
345 div 456 = 34 False
5247 div 1 = 524 False
1234567 mod 10 = 7 True
4567 mod 100 = 67 True
(4567 div 100) mod 10 = 5
4. Computational thinking, problem-solving and programming 42 / 192

More logical Expressions

A logical expression is either True (sometimes represented with 1) or


False (sometimes represented with 0).
Determine the value of the following logical expressions.
Expression Truth Value
5 mod 2 = 0 False
3 mod 7 = 7 False
25 mod 26 = 25 True
25 div 26 = 0 True
5 div 4 = 2 False
5678 mod 26 = 27 False
345 div 456 = 34 False
5247 div 1 = 524 False
1234567 mod 10 = 7 True
4567 mod 100 = 67 True
(4567 div 100) mod 10 = 5 True
4. Computational thinking, problem-solving and programming 43 / 192

More Logical Expressions

Give values for X and Y such that


X + Y > 5 is true
4. Computational thinking, problem-solving and programming 43 / 192

More Logical Expressions

Give values for X and Y such that


X + Y > 5 is true (X = 5, Y = 1)
X mod 2 = Y is true
4. Computational thinking, problem-solving and programming 43 / 192

More Logical Expressions

Give values for X and Y such that


X + Y > 5 is true (X = 5, Y = 1)
X mod 2 = Y is true (X = 7, Y = 1)
(X div 5) + 2 > 4 is true
4. Computational thinking, problem-solving and programming 43 / 192

More Logical Expressions

Give values for X and Y such that


X + Y > 5 is true (X = 5, Y = 1)
X mod 2 = Y is true (X = 7, Y = 1)
(X div 5) + 2 > 4 is true (X = 35)
X mod Y = 3
4. Computational thinking, problem-solving and programming 43 / 192

More Logical Expressions

Give values for X and Y such that


X + Y > 5 is true (X = 5, Y = 1)
X mod 2 = Y is true (X = 7, Y = 1)
(X div 5) + 2 > 4 is true (X = 35)
X mod Y = 3 (X = 3, Y = 10)
4. Computational thinking, problem-solving and programming 44 / 192

Example

Write an algorithm in IB Pseudocode that takes a natural number ≤ 99


as input and prints its digits.
For example if the input is 75 the program should print 7 and 5 in the
output.
4. Computational thinking, problem-solving and programming 44 / 192

Example

Write an algorithm in IB Pseudocode that takes a natural number ≤ 99


as input and prints its digits.
For example if the input is 75 the program should print 7 and 5 in the
output.
 
1 input A
2 X = A div 10
3 Y = A mod 10
4 output " The first digit is " ,X , " . The second digit is " , Y
 
4. Computational thinking, problem-solving and programming 45 / 192

Example

Write an algorithm in IB Pseudocode that takes a natural number ≤ 999


as input and prints its digits.
For example if the input is 175 the program should print 1, 7 and 5 in the
output.
4. Computational thinking, problem-solving and programming 45 / 192

Example

Write an algorithm in IB Pseudocode that takes a natural number ≤ 999


as input and prints its digits.
For example if the input is 175 the program should print 1, 7 and 5 in the
output.
 
1 input A
2 X = A div 100 // hundreds
3 Y = ( A div 10) mod 10 // tens
4 W = A mod 10 // units
5 if X > 0 then // if X = 0 , do not print it
6 output X
7 end if
8 if Y > 0 then // if Y = 0 , do not print it
9 output Y
10 end if
11 output W
 
4. Computational thinking, problem-solving and programming 46 / 192

Example (1st solution)


Write an algorithm in IB Pseudocode that takes X as input, where X is a
natural number ≤ 999 and counts the number of digits of X that are
equal to 5. For example if the input is 575 the algorithm should print 2.
 
1 input A
2 if A div 100 = 5 then
3 B =1
4 else
5 B =0
6 end if
7 if ( A div 10) mod 10 = 5 then
8 C = 1
9 else
10 C =0
11 end if
12 if A mod 10 = 5 then
13 D = 1
14 else
15 D =0
16 end if
17 E = B + C + D
18 output E
 
4. Computational thinking, problem-solving and programming 47 / 192

Example (2nd solution)

Write an algorithm in IB Pseudocode that takes X as input, where X is a


natural number ≤ 999 and counts the number of digits of X that are
equal to 5. For example if the input is 575 the algorithm should print 2.
If the input is 622 the algorithm should print 0.
 
1 input A
2 B = 0 // number of digits
3 if A div 100 = 5 then // check if hundreds is equal to 5
4 B = B + 1
5 end if
6 if ( A div 10) mod 10 = 5 then // check if tens is equal to 5
7 B = B + 1
8 end if
9 if A mod 10 = 5 then // check if unit is equal to 5
10 B = B + 1
11 end if
12 output B
 
4. Computational thinking, problem-solving and programming 48 / 192

Example

What will the following code print


 
1 X = 10
2 if X mod 3 = 0 then
3 print " Hello ! "
4 else
5 print " Goodbye ! "
6 end if
 
4. Computational thinking, problem-solving and programming 48 / 192

Example

What will the following code print


 
1 X = 10
2 if X mod 3 = 0 then
3 print " Hello ! "
4 else
5 print " Goodbye ! "
6 end if
 
It will print “Goodbye!”.
4. Computational thinking, problem-solving and programming 49 / 192

Example

What will the following code print


 
1 input X
2 A = 7
3 if ( X +5) div 3 = 2 then
4 A = A + X
5 else
6 A = A*X
7 end if
8 A = A mod 4
9 output A
 
1 if we give 5 as input for X ?
2 if we give 2 as input for X ?
3 if we give 0 as input for X ?
4. Computational thinking, problem-solving and programming 50 / 192

Nested ifs

The if commands can be nested (that means an if can be inside another


if).
What will the following code print?
 
1 X = 5
2 A = 3
3 B = 2
4 if 12 mod X = 2 then
5 X = 56 * A - B
6 if A + B > 5 then
7 output X
8 end if
9 else
10 A = A + 2
11 B = 4 + X
12 output B
13 end if
 
4. Computational thinking, problem-solving and programming 50 / 192

Nested ifs

The if commands can be nested (that means an if can be inside another


if).
What will the following code print?
 
1 X = 5
2 A = 3
3 B = 2
4 if 12 mod X = 2 then
5 X = 56 * A - B
6 if A + B > 5 then
7 output X
8 end if
9 else
10 A = A + 2
11 B = 4 + X
12 output B
13 end if
 
It will print nothing!
4. Computational thinking, problem-solving and programming 51 / 192

Nested ifs
The most interesting case is when the if follows the else of an earlier if.
A long jump athlete has achieved the scores A, B and C in meters. Write an algorithm that reads
A, B and C and does the following:
computes the average of A, B and C , call it AVG , and prints it
if AVG ≥ 8 it prints “You have passed”
if 7.5 ≤ AVG < 8 it prints “You failed but you were close”
if AVG < 7.5 it prints “You failed :(”
 
1 input A
2 input B
3 input C
4 AVG = ( A + B + C ) /3
5 if AVG >= 8 then
6 output " You have passed "
7 else
8 if AVG >= 7.5 then
9 output " You failed but you were close "
10 else
11 output " You failed :( "
12 end if
13 end if
 
4. Computational thinking, problem-solving and programming 52 / 192

Example
 
1 input A
2 if A > 11 then
3 B = A div 3
4 B = 2 * B // command 1
5 else
6 if A > 3 then
7 B = A * 2
8 B = B mod 3 // command 2
9 else
10 B = A * A
11 B = B div 2 // command 3
12 end if
13 end if
14 output B
 
1 Which command will be executed and what will be the output if the
input for A is 11?
2 Which command will be executed and what will be the output if the
input for A is 3?
3 Find two values for A such that command 2 will be executed.
4 Find two values for A such that command 3 will not be executed.
4. Computational thinking, problem-solving and programming 53 / 192

Example
A store puts discounts on some of its products according to the following
table.
Value Discount
. . . ≤ 200 10%
200 < . . . ≤ 300 20%
300 < . . . 30%
Write an algorithm that takes as input the original value of a product and
computes its final value (after the discount) using the above table.
 
1 input V
2 if V <= 200 then
3 V = V - V /10
4 else
5 if V > 300 then
6 V = V - V * 0.3
7 else
8 V = V - V * 0.2
9 end if
10 end if
11 output V
 
4. Computational thinking, problem-solving and programming 54 / 192

Iterations

Assume that we want to print all the numbers from 1 to 10. We could
write the following code
 
1 output 1
2 output 2
3 output 3
4 output 4
5 output 5
6 output 6
7 output 7
8 output 8
9 output 9
10 output 10
 
4. Computational thinking, problem-solving and programming 54 / 192

Iterations

Assume that we want to print all the numbers from 1 to 10. We could
write the following code
 
1 output 1
2 output 2
3 output 3
4 output 4
5 output 5
6 output 6
7 output 7
8 output 8
9 output 9
10 output 10
 
Does this look practical?
4. Computational thinking, problem-solving and programming 55 / 192

Loops

In programming loops are pieces of code that will be executed iteratively.


Using a loop in IB pseudocode we can print all the numbers from 1 to 10 as
follows
 
1 loop I from 1 to 10
2 output I
3 end loop
 
In the above code the command “output I”, is executed exactly 10 times. One
for each value of I.
4. Computational thinking, problem-solving and programming 56 / 192

Loops
The following two algorithms are equivalent.
I = 1
output I
I = 2
output I
I = 3
output I
I = 4
output I
I = 5
loop I from 1 to 10
output I
output I
I = 6
end loop
output I
I = 7
output I
I = 8
output I
I = 9
output I
I = 10
output I
4. Computational thinking, problem-solving and programming 57 / 192

Example

Write an algorithm that prints all the multiples of 5 that are less or equal
to 1000.
 
1 loop I from 0 to 1000
2 if I mod 5 = 0 then
3 output I
4 end if
5 end loop
 
4. Computational thinking, problem-solving and programming 58 / 192

Example

Write an algorithm the squares of all the numbers from 0 to 100.


 
1 loop I from 0 to 100
2 output I ^2
3 end loop
 
4. Computational thinking, problem-solving and programming 59 / 192

Example
Using a loop write an algorithm that computes the sum of the numbers
from 1 to 1000.
SUM = 0
loop I from 1 to 1000
SUM = SUM + I
end loop
output SUM

which is equivalent to:


SUM = 0
I = 1
SUM = SUM + I
I = 2
SUM = SUM + I
I = 3
SUM = SUM + I
.
.
.
SUM = SUM + I
output SUM
4. Computational thinking, problem-solving and programming 60 / 192

Example

Using a loop write an algorithm that computes the product of all the
numbers from 1 to 1000.
PRODUCT = 1
loop N from 1 to 1000
PRODUCT = PRODUCT * N
end loop
output PRODUCT

which is equivalent to:


PRODUCT = 1
N = 1
PRODUCT = PRODUCT * N
N = 2
PRODUCT = PRODUCT * N
.
.
.
N = 1000
PRODUCT = PRODUCT * N
4. Computational thinking, problem-solving and programming 61 / 192

Example

Write an algorithm that takes a number N as input and prints all the
factors of N.
For example if the input is 15 the algorithm should print 1, 3, 5 and 15.
 
1 input N
2 loop X from 1 to N
3 if N mod X = 0 then // we check whether X is a factor of N
4 output X
5 end if
6 end loop
 
4. Computational thinking, problem-solving and programming 62 / 192

Boolean Values

Except for numerical values (i.e. numbers), variables may also take
boolean values.
What will the following algorithm print if X = 18? If X = 115?
 
1 input X
2 A = false
3 if X mod 2 = 0 then
4 A = true
5 end if
6 if A = true then
7 output " The number you gave is even "
8 else
9 output " The number you gave is odd "
10 end if
 
The purpose of boolean values is to check whether something holds or
not. Of course, as you know from topic 2, many people prefer using 1
instead of true and 0 instead of false.
4. Computational thinking, problem-solving and programming 63 / 192

Example

Write an algorithm that takes a number N and checks whether N is


prime. If N is prime then the algorithm should print “The number is
prime”. Otherwise it should print “The number is not prime”.
 
1 input N
2 PRIME = true // initially we assume that N is prime
3 loop I from 2 to N -1
4 if N mod I = 0 then // if we find a factor
5 PRIME = false // we denote that N is not prime
6 end if
7 end loop
8 if PRIME = true AND N 6= 1 then
9 output " The number is prime "
10 else
11 output " The number is not prime "
12 end if
 
4. Computational thinking, problem-solving and programming 64 / 192

Example

Write an algorithm that takes A and B as input and outputs the solutions
(if any) of the equation A · x + B = 0. Make sure that your algorithm
provides the correct output for all the possible values of A and B.
 
1 input A
2 input B
3 if A = 0 then
4 if B = 0 then
5 output " Infinite solutions "
6 else
7 output " No solutions "
8 end if
9 else
10 X = - B /A
11 output " The only solution is " , X
12 end if
 
4. Computational thinking, problem-solving and programming 65 / 192

Example

Write an algorithm that takes A, B and C as input and outputs the


solutions (if any) of the equation A · x 2 + B · x + C = 0. Make sure that
your algorithm provides the correct output for all the possible values of
A, B and C .
4. Computational thinking, problem-solving and programming 66 / 192

 
1 input A
2 input B
3 input C
4 if A = 0 then // we solve B * X + C = 0
5 if B = 0 then
6 if C = 0 then
7 output " Infinite solutions "
8 else
9 output " No solutions "
10 end if
11 else
12 X = - C /B
13 output " The only solution is " , X
14 end if
15 else // we truly have a second degree equation
16 D = B ^2 - 4 * A * C
17 if D > = 0 then √
18 X1 = ( - B + √D ) /(2 * A )
19 X2 = ( - B - D ) /(2 * A )
20 output " The solutions are " , X1 , X2
21 else
22 output " No real solutions "
23 end if
24 end if
 
4. Computational thinking, problem-solving and programming 67 / 192

Example

Write an algorithm that takes as input a number of seconds and outputs


the corresponding number of hours, minutes and seconds.
For example if the input is 3620 the algorithm should print 1 hour, 0
minutes and 20 seconds.
 
1 input A
2 if A >= 3600 then
3 B = A div 3600
4 output B , " hours and "
5 end if
6 C = A mod 3600
7 D = C div 60
8 output D , " minutes and "
9 E = C mod 60
10 output E , " seconds "
 
4. Computational thinking, problem-solving and programming 68 / 192

Example

Write an algorithm that prints the sum of the factors of a given number
N. For example if N = 6, the algorithm should print 12, since
12 = 6 + 3 + 2 + 1.
 
1 input N
2 SUM = 0
3 loop I from 1 to N
4 if N mod I = 0 then
5 SUM = SUM + I
6 end if
7 end loop
8 output " The sum is " , SUM
 
4. Computational thinking, problem-solving and programming 69 / 192

Past Paper Question

Trace the following algorithmic fragment for N=6. Show all working in a
trace table.
SUM = 0
loop COUNT from 1 to ( N div 2)
if N mod COUNT = 0 then
SUM = SUM + COUNT COUNT SUM N mod COUNT = 0 output
0
end if
1 1 TRUE
end loop 2 3 TRUE
if SUM = N then 3 6 TRUE
output " perfect " perfect
else
output " not perfect "
end if
4. Computational thinking, problem-solving and programming 70 / 192

Trace the algorithm

There are no standard rules when tracing algorithms. However your


tables should contain at least the following
1 a column for every variable. This column should contain all the
values taken by the variable in the correct row
2 a column for every condition (from if statements, while and for
loops) and the values taken by the conditions in the correct row
3 a column called output that should contain everything that is
printed by the algorithm in the correct row
Sometimes it could be fine, if you forget some variables and some
conditions (especially when their values are always the same or if they
change only once). Also the IB question will hopefully tell you which
column names you should use . . .
4. Computational thinking, problem-solving and programming 71 / 192

Trace the algorithm

Trace the following algorithmic fragment for N=5. Show all working in a
trace table.
PRODUCT = 1
loop I FROM 1 to N
if I mod 2 = 0 then
PRODUCT = PRODUCT * I
else
PRODUCT = PRODUCT - I
end if
end loop
output PRODUCT
4. Computational thinking, problem-solving and programming 72 / 192

The while loop

In programming it is often the case that we wish to repeat a piece of


code as long as a condition holds.
The next algorithm prints all numbers from 1 to 5
 
1 X = 1
2 loop while X <= 5
3 output X
4 X = X + 1
5 end loop
 

X <= 5 X output
TRUE 1 1
TRUE 2 2
TRUE 3 3
TRUE 4 4
TRUE 5 5
FALSE 6
4. Computational thinking, problem-solving and programming 73 / 192

The while loop

In the while loop the condition is checked every time before entering the
loop. When the condition is not met any more the loop stops.
After the following algorithm what is the value of X ?
 
1 X = 1
2 loop while X <= 5
3 output X
4 X = X +1
5 end loop
 
4. Computational thinking, problem-solving and programming 73 / 192

The while loop

In the while loop the condition is checked every time before entering the
loop. When the condition is not met any more the loop stops.
After the following algorithm what is the value of X ?
 
1 X = 1
2 loop while X <= 5
3 output X
4 X = X +1
5 end loop
 
After the while loop is executed it holds that X = 6
4. Computational thinking, problem-solving and programming 74 / 192

Loops

The following two algorithms are equivalent.


X = 1
loop while X <= 5 loop X from 1 to 5
output X output X
X = X +1 end loop
end loop
4. Computational thinking, problem-solving and programming 75 / 192

While loops may not terminate

 
1 X = 1
2 loop while X > 0
3 X = X + 1
4 end loop
 
4. Computational thinking, problem-solving and programming 76 / 192

Loops may not start!

It is possible that while and for loops may not even start!
 
1 X = 0
2 loop while X > 1
3 X = X + 1
4 end loop
 
 
1 loop X from 5 to 1
2 output X
3 end loop
 
4. Computational thinking, problem-solving and programming 77 / 192

Example

Trace the following algorithm for N = 5.


input N N I S I mod 2 = 0 output
S = 0 5 0
loop I from 1 to N 1 FALSE
if I mod 2 = 0 then 2 2 TRUE
S = S + I 3 FALSE
end if 4 6 TRUE
end loop 5 FALSE
6
output S
4. Computational thinking, problem-solving and programming 78 / 192

Example

Give a value for N such that the following algorithm prints


a. 5
b. 9
c. 15
 
1 input N
2 X = 5
3 loop A from 1 to N
4 X = X + 2
5 end loop
6 output X
 
a. any integer value less than 1
b. N=2
c. N=5
4. Computational thinking, problem-solving and programming 79 / 192

Different Uses of the equality symbol =

In the following code we have an assignment statement. That means


that the memory location that is represented with the name X is
assigned the value 5.
 
1 X = 5
 
In the following code we have equality checks. That means that we are
checking whether the memory location that is represented with the name
X contains the value 5.
 
1 if X = 5 then
2 ...
3 end if
4 loop while X = 5 then
5 ...
6 end if
 
4. Computational thinking, problem-solving and programming 80 / 192

Example

Use a while loop in order to write an algorithm that prints all the
multiples of 7 that are less than or equal to 10000.
1st solution
 
1 I = 0
2 loop while I <= 10000
3 if I mod 7 = 0 then
4 output I
5 end if
6 I = I + 1
7 end loop
 
2nd solution
 
1 X =0
2 loop while X <= 10000
3 output X
4 X = X + 7
5 end loop
 
4. Computational thinking, problem-solving and programming 81 / 192

Complexity of Algorithms

loop I from 0 to 10000 I = 0


if I mod 7 = 0 then loop while I <= 10000
output I output I
end if I = I + 7
end loop end loop

Which of the above algorithms is faster and why?


In the algorithm to left we make 10001 checks, while in the algorithm to
the right we make only 10000 div 7 + 1 = 1429.
4. Computational thinking, problem-solving and programming 82 / 192

Question
Should we care about the complexity of the algorithms?
4. Computational thinking, problem-solving and programming 82 / 192

Question
Should we care about the complexity of the algorithms?

When designing algorithms the following rules should be followed:


1 First do it (i.e. first produce a solution that outputs some kind of
result.
2 Then do it right (i.e. as a second step produce a solution that
functions correctly)
3 Then do it fast (i.e. then produce a solution that is as fast as
possible)
For the IB examinations you should not care about step 3. Hence, the
answer to the above question, is no. At least for the IB examination :)
In other words in the exams it is only expected that you produce correct
(and not fast) algorithms.
4. Computational thinking, problem-solving and programming 83 / 192

Past Paper Question

Trace the following fragment for N=139 and L=3, by copying and
completing the trace table given below.
D = N div L
Z = 1
B = false
loop while Z < L D Z B Z <L output
D = D div L 46 1 false
Z = Z + 1 15 1 true true
B = NOT B
end loop 5 2 false true
if ( D 6= 0 AND B ) then 3 false
output (D , B ) 3, true
else
output (Z , NOT B )
end if
4. Computational thinking, problem-solving and programming 84 / 192

Arrays
An array is a way of storing related data in a row. Data could be
numbers, strings, characters, etc.
In an array data can be identified using a unique number called index.
The length of the array is the number of data stored in the array.
The indices of the array start 0 and go up to the length of the array
minus one.
The following is an example of an array of length 5 that contains integers.

index 0 1 2 3 4
data -11 53 137 8 1234

Arrays are typically be used for storing related data:


an array may hold the scores of a student in 10 exams
an array may hold the temperatures that were measured during a
week in Athens
an array may hold the salaries earned by 10 employees
4. Computational thinking, problem-solving and programming 85 / 192

Arrays

The indices of an array will never be given. It will always be assumed


that the indices start from 0.
Arrays have names. For example the following array stores the grades of
a student and is called Scores.
77 89 95 79 84 99 100

The element at position 0 is represented as Scores[0]


The element at position 1 is represented as Scores[1]
...
The element at position i is represented as Scores[i]
What is the length of the array Scores?
What is the position of the last element of the array Scores?
What is the value of Scores[5]?
What is the value of Scores[3]?
4. Computational thinking, problem-solving and programming 86 / 192

Array

Let the array Scores be as follows:


77 89 95 79 84 99 100

Scores[i] is pronounced as “Scores of i” or as “the element of array


Scores in position i” and behaves as normal variable.
So, in the example here it holds that Scores[3]=79.
If we set Scores[3]= 25 then the array looks like
77 89 95 25 84 99 100

If we set Scores[3]= Scores[3]+2 then the array looks like


4. Computational thinking, problem-solving and programming 86 / 192

Array

Let the array Scores be as follows:


77 89 95 79 84 99 100

Scores[i] is pronounced as “Scores of i” or as “the element of array


Scores in position i” and behaves as normal variable.
So, in the example here it holds that Scores[3]=79.
If we set Scores[3]= 25 then the array looks like
77 89 95 25 84 99 100

If we set Scores[3]= Scores[3]+2 then the array looks like


77 89 95 27 84 99 100
4. Computational thinking, problem-solving and programming 87 / 192

Arrays in IB Pseudocode

Index 0 1 2 3 4
Data -11 53 137 8 1234
Write an algorithm that prints all the elements of the above array Scores.
 
1 loop I from 0 to 4
2 output Scores [ I ]
3 end loop
 
which is equivalent to
 
1 output Scores [0]
2 output Scores [1]
3 output Scores [2]
4 output Scores [3]
5 output Scores [4]
 
4. Computational thinking, problem-solving and programming 88 / 192

Arrays in IB Pseudocode

-11 53 137 8 1234

Write an algorithm that prints the sum of the elements of the above
array Scores.
 
1 SUM = 0
2 loop I from 0 to 4
3 SUM = SUM + Scores [ I ]
4 end loop
5 output " The sum of the elements is " , sum
 
4. Computational thinking, problem-solving and programming 89 / 192

Arrays in IB Pseudocode

Write an algorithm that prints the product of the non-zero elements in an


array Scores of N elements.
 
1 PRODUCT =1
2 loop I from 0 to N - 1
3 if Scores [ I ] 6= 0 then
4 PRODUCT = PRODUCT * Scores [ I ]
5 end if
6 end loop
7 output " The product is " , PRODUCT
 
4. Computational thinking, problem-solving and programming 90 / 192

Arrays in IB Pseudocode

Write an algorithm that checks whether an array A of N elements has


negative values.
If the array has at least one negative value the algorithm should print the
message “There is a negative value” only once.
If all the values in the array are non-negative the algorithm should print
“All values are non-negative”.
 
1 NEG = false // this variables tells whether
2 // there is a negative value
3 loop I from 0 to N -1
4 if A [ I ] < 0 then
5 NEG = true
6 end if
7 end loop
8 if NEG then // this is equivalent to if NEG = true
9 output " There is a negative value "
10 else
11 output " All values are non - negative "
12 end if
 
4. Computational thinking, problem-solving and programming 91 / 192

Arrays in IB Pseudocode

Write an algorithm that prints the elements of an array A of length N in


reverse order. That the element A[N-1], should be printed first, the
element A[N-2] second, . . . and the element A[0] last.
 
1 X = N -1
2 loop while X >= 0
3 output A [ X ]
4 X = X -1
5 end loop
 
 
1 loop X from 0 to N -1
2 output A [N -1 - X ]
3 end loop
 
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
Hence X mod 10 is equal to the last digit of X.
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
Hence X mod 10 is equal to the last digit of X.
25 div 10 = 2
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
Hence X mod 10 is equal to the last digit of X.
25 div 10 = 2
123 div 10 = 12
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
Hence X mod 10 is equal to the last digit of X.
25 div 10 = 2
123 div 10 = 12
456 div 10 = 45
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
Hence X mod 10 is equal to the last digit of X.
25 div 10 = 2
123 div 10 = 12
456 div 10 = 45
2342356 div 10 = 234235
4. Computational thinking, problem-solving and programming 92 / 192

Div and mod

25 mod 10 = 5
123 mod 10 = 3
2342356 mod 10 = 6
Hence X mod 10 is equal to the last digit of X.
25 div 10 = 2
123 div 10 = 12
456 div 10 = 45
2342356 div 10 = 234235
Hence X div 10 discards the last digit of X.
4. Computational thinking, problem-solving and programming 93 / 192

Example

Let A be an array of N integers. Construct an algorithm that prints the


number of odd and the number of even elements in A.
 
1 EVEN = 0
2 loop I from 0 to N -1
3 if A [ I ] mod 2 = 0 then
4 EVEN = EVEN + 1
5 end if
6 end loop
7 output " The number of even elements is " , EVEN
8 ODD = N - EVEN
9 output " The number of even elements is " , ODD
 
4. Computational thinking, problem-solving and programming 94 / 192

Example
Assume that the grades of N students in Mathematics are stored in array
called SCORES. The grades are integers from 0 to 100. A student has
passed if he/she has scored at least 50. Construct an algorithm that
Prints the number of students that have passed
Prints the average grade of the students that have passed.
 
1 PASSED = 0
2 SUM = 0
3 loop I from 0 to N -1
4 if SCORES [ I ] >= 50 then
5 PASSED = PASSED + 1
6 SUM = SUM + SCORES [ I ]
7 end if
8 end loop
9 if PASSED > 0 then
10 output PASSED , " students have passed "
11 AVG = SUM / PASSED
12 output " The average of the students that passed is " , AVG
13 else
14 output " No students passed "
15 end if
 
4. Computational thinking, problem-solving and programming 95 / 192

Past Paper Question

Trace the following algorithm. Show all your working in a table.


 
1 K = 1
2 N = 1
3 M = 2
4 loop while K < 5
5 output (N , M )
6 K = K + 1
7 N = N + 2
8 M = M * 2
9 end loop
 

K N M K < 5? output
1 1 2 true 1, 2
2 3 4 true 3, 4
3 5 8 true 5,8
4 7 16 true 7 , 16
5 9 32 false
4. Computational thinking, problem-solving and programming 96 / 192

Past Paper Question

A sub-program all_even() accepts a positive integer N and outputs true


if all digits of N are even, otherwise it outputs false. For example,
all_even(246) outputs true and all_even(256) outputs false.
The following algorithm is constructed for the sub-program
all_even(N).
 
1 EVEN = true
2 loop while ( N > 0) and ( EVEN = true )
3 if ( N mod 10) mod 2 = 1 then
4 EVEN = false
5 end if
6 end loop
7 output EVEN
 
1 Explain why this algorithm does not obtain the correct result.
2 Outline what should be changed in the algorithm to obtain the
correct result.
4. Computational thinking, problem-solving and programming 97 / 192

 
1 EVEN = true
2 loop while ( N > 0) and ( EVEN = true )
3 if ( N mod 10) mod 2 = 1 then
4 EVEN = false
5 end if
6 N = N div 10 // we forget the last digit of N
7 end loop
8 output EVEN
 

N EVEN (N > 0) and (EVEN = true) (N mod 10) mod 2 = 1 output


468 true true false
46 true false
4 true false
0 false
true
N EVEN (N > 0) and (EVEN = true) (N mod 10) mod 2 = 1 output
458 true true false
45 false true true
4 false
false
4. Computational thinking, problem-solving and programming 98 / 192

Example

Construct an algorithm that takes an integer N as input and computes


N! (the factorial of N). For example if N = 6 the algorithm should print
720 = 6 · 5 · · · 2 · 1 = 6!. Remember that N! is defined as follows:
(
1 ,N = 0
N! =
N · N − 1··· · 2 · 1 ,N > 0
 
1 input N
2 PRODUCT = 1
3 loop I from 1 to N
4 PRODUCT = I * PRODUCT
5 end loop
6 output PRODUCT
 
4. Computational thinking, problem-solving and programming 99 / 192

Past Paper Question (1st Solution without loop)


Assume that we have a new programming language. One of the
predefined sub-programs in the new language is sumOdd(N) . It accepts
an integer N as input. If N<=0 it returns -1 , otherwise it returns the sum
of the first N odd positive numbers.
For example: sumOdd(4) returns 16 , because 4 is not less than 0, and 1
+ 3 + 5 + 7 = 16. sumOdd(-3) returns - 1 , because -3 is less than 0.
Construct an algorithm for the sub-program sumOdd().
 
1 sumOdd ( N )
2 if N <=0 then
3 return -1
4 end if
5 return N ^2
6 end sumOdd
 
Since, the N-the odd number is 2(N − 1) + 1. The sum of the first N
odd numbers is, by arithmetical sequence

N(1 + 2(N − 1))


= N2
2
4. Computational thinking, problem-solving and programming 100 / 192

Past Paper Question (2st Solution with loop)


Assume that we have a new programming language. One of the
predefined sub-programs in the new language is sumOdd(N) . It accepts
an integer N as input. If N<=0 it returns -1 , otherwise it returns the sum
of the first N odd positive numbers.
For example: sumOdd(4) returns 16 , because 4 is not less than 0, and 1
+ 3 + 5 + 7 = 16. sumOdd(-3) returns - 1 , because -3 is less than 0.
Construct an algorithm for the sub-program sumOdd().
 
1 sumOdd ( N )
2 SUM = 0
3 if N <=0 then
4 return -1
5 else
6 loop I from 1 to 2*( N -1) +1
7 if I mod 2 <> 0 then
8 SUM = SUM + I
9 end if
10 end loop
11 return SUM
12 end if
13 end sumOdd
 
4. Computational thinking, problem-solving and programming 101 / 192

Past Paper Question (3rd Solution with loop)


Assume that we have a new programming language. One of the
predefined sub-programs in the new language is sumOdd(N) . It accepts
an integer N as input. If N<=0 it returns -1 , otherwise it returns the sum
of the first N odd positive numbers.
For example: sumOdd(4) returns 16 , because 4 is not less than 0, and 1
+ 3 + 5 + 7 = 16. sumOdd(-3) returns - 1 , because -3 is less than 0.
Construct an algorithm for the sub-program sumOdd().
 
1 sumOdd ( N )
2 if N <=0 then
3 return -1
4 else
5 SUM = 0
6 ODD = 1
7 loop I from 1 to N
8 SUM = SUM + ODD
9 ODD = ODD +2
10 end loop
11 return SUM
12 end if
13 end sumOdd
 
4. Computational thinking, problem-solving and programming 102 / 192

Example

Construct an algorithm that takes 2 numbers as input and outputs their


minimum.
 
1 input A
2 input B
3 if A < B then
4 output A
5 else
6 output B
7 end if
 
 
1 input A
2 input B
3 min = A
4 if B < min then
5 min = B
6 end if
7 output min
 
4. Computational thinking, problem-solving and programming 103 / 192

Example

How can you extend the previous algorithm to to 3 elements?


 
1 input A
2 input B
3 input C
4 min = A
5 if B < min then
6 min = B
7 end if
8 if C < min then
9 min = C
10 end if
11 output min
 
4. Computational thinking, problem-solving and programming 104 / 192

Example

How can you extend the previous algorithm to to 4 elements?


 
1 input A
2 input B
3 input C
4 input D
5 min = A
6 if B < min then
7 min = B
8 end if
9 if C < min then
10 min = C
11 end if
12 if D < min then
13 min = D
14 end if
15 output min
 
4. Computational thinking, problem-solving and programming 105 / 192

Example

Let A be an array of N integers. Construct an algorithm that finds the


minimum element of A.
 
1 min = A [0]
2 loop I from 1 to N -1
3 if A [ I ] < min then
4 min = A [ I ]
5 end if
6 end loop
7 output min
 
4. Computational thinking, problem-solving and programming 106 / 192

Solve exercise 10 from past paper 1 (SL) from Friday 2 November 2018
(except
a 26
b
 
1 input BMI
2 if BMI < 18.5 then
3 output " underweight "
4 else
5 if BMI < 25.0 then
6 output " normal weight "
7 else
8 if BMI < 30.0 then
9 output " overweight "
10 else
11 output " obese "
12 end if
13 end if
14 end if
 
4. Computational thinking, problem-solving and programming 107 / 192

d
 
1 // we calculate the average BMI of the group
2 SUM = 0
3 loop I from 0 to 29
4 BMI = calcBMI ( HEIGHT [ I ] , WEIGHT [ I ])
5 SUM = SUM + BMI
6 end loop
7 AVG = SUM /30
8 // we print the names of the people in the group
9 // who have greater BMI than the average
10 loop I from 0 to 29
11 BMI = calcBMI ( HEIGHT [ I ] , WEIGHT [ I ])
12 if ( BMI > AVG ) then
13 output NAME [ I ]
14 end if
15 end loop
 
4. Computational thinking, problem-solving and programming 108 / 192

Solve exercise 10 from past paper 1 (SL) from Friday 4 November 2016
(except part (d)).
b
 
1 input LOCKER
2 if LOCKER mod 4 = 0 then
3 output " blue "
4 end if
5 if LOCKER mod 4 = 1 then
6 output " red "
7 end if
8 if LOCKER mod 4 = 2 then
9 output " white "
10 end if
11 if LOCKER mod 4 = 3 then
12 output " yellow "
13 end if
 
4. Computational thinking, problem-solving and programming 109 / 192

c
 
1 COUNT = 0
2 loop I from 0 to 2399
3 if PAINTED [ I ] = true then
4 COUNT = COUNT + 1
5 end if
6 end loop
7 output " The number of lockers that have been painted so
far
8 is " , COUNT
 
4. Computational thinking, problem-solving and programming 110 / 192

Assume that we have the following array A


4 5 -1 3 6 7 8

Trace the following algorithm.


 
1 SUM = 0
2 loop I from 0 to 5
3 A [ I ] = 2 * A [ I +1] // e . g if I = 0 the A [0] = 2 * A [1]
4 SUM = SUM + A [ I ] // e . g if I = 0 the SUM = SUM + A [0]
5 end loop
6 output SUM
 

SUM I A[0] A[1] A[2] A[3] A[4] A[5] A[6] output


0 4 5 -1 3 6 7 8
10 0 10
8 1 -2
14 2 6
26 3 12
40 4 14
56 5 16
56
4. Computational thinking, problem-solving and programming 111 / 192

Algorithm Flowcharts

An algorithm can also be represented as a flowchart, using the following


notation.

input or output

condition check

calculation
4. Computational thinking, problem-solving and programming 112 / 192

Past Paper Question


Consider the following algorithm that inputs X and N, and outputs P

a. Determine how many times multiplication is performed when the


algorithm is executed.
b. Construct a trace table for the algorithm when X=2 and N=4.
c. State the purpose of the algorithm.
4. Computational thinking, problem-solving and programming 113 / 192

Answer

a. If N ≤ 0 then the multiplication is executed 0 times. If N > 0 then


the multiplication is executed N times.
X N P N > 0 output
2 4 1 true
3 2 true
b. 2 4 true
1 8 true
0 16 false
16
c. If N ≥ 0 then it raises X to the power of N. Of N < 0 it prints 1.
4. Computational thinking, problem-solving and programming 114 / 192

Convert the algorithm in the previous slide in IB pseudocode


 
1 input X
2 input N
3 P = 1
4 loop while N > 0
5 P = P * X
6 N = N- 1
7 end loop
8 output P
 
4. Computational thinking, problem-solving and programming 115 / 192

Notation

Let A be an array. Then A.length is equal to the length of a the array.


For example if A is the following array
5 7 6 -3 5 7 10

then A.length = 7
4. Computational thinking, problem-solving and programming 116 / 192

Linear (or Sequential) Search

Assume that we have the following array A


5 7 6 -3 5 7 10

How can we search for element X in the above array?


 
1 input X
2 FOUND = false
3 loop I from 0 to A . length -1
4 if X = A [ I ] then
5 FOUND = true
6 end if
7 end loop
8 output FOUND
 
4. Computational thinking, problem-solving and programming 117 / 192

Linear Search (Optimized)


Assume that we have the following array A
5 7 6 -3 5 7 10

Construct an algorithm that searches for element X in the above array.


Your algorithm should stop when the element is found.
 
1 input X
2 FOUND = false
3 I = 0
4 loop while ( I < A . length ) AND ( NOT FOUND )
5 if X = A [ I ] then
6 FOUND = true
7 end if
8 I = I + 1
9 end loop
 

Remark
In the optimized version of linear search the algorithm stops exactly when
the first occurrence of X is found.
4. Computational thinking, problem-solving and programming 118 / 192

Linear Search (Optimized)


Trace the following algorithm for X = -3
5 7 6 -3 5
 
1 input X
2 FOUND = false
3 I = 0
4 loop while ( I < A . length ) AND ( NOT FOUND )
5 if X = A [ I ] then
6 FOUND = true
7 end if
8 I = I + 1
9 end loop
10 output FOUND
 
(I < A.length) AND (NOT FOUND)? X = A[I]? FOUND I X output
false 0 -3
true false 1
true false 2
true false 3
true true true 4
false true
4. Computational thinking, problem-solving and programming 119 / 192

Array Bounds

Let A be an array. The indices of A’s elements start at 0 and end at


A.length − 1.
E.g. if A is the following array
5 7 6 -3 5

Then A.length = 5 and the indices of A’s elements start at 0 and end at
4. Writing A[5], A[7] or A[-1] is wrong and can produce an error!
And in general we cannot write A[A.length] or A[A.length + 5]. So it is
good idea to verify that I ≥ 0 and I < A.length before writing A[I ].
4. Computational thinking, problem-solving and programming 120 / 192

Arrays bounds

The following pieces of code are wrong and will produce errors!
 
1 I = 0
2 loop while ( I <= A . length )
3 output A [ I ]
4 I = I +1
5 end loop
 
 
1 loop I from 0 to A . length
2 output A [ I ]
3 end loop
 
4. Computational thinking, problem-solving and programming 121 / 192

Linear (or Sequential) Search

Arrays may contains strings as well.

Mike Thanos Greg Freedom Jason Liberta Michael Jordan

How can we search for element X in the above array?


 
1 input X // we read a string from the input
2 FOUND = false
3 I = 0
4 loop while ( I < A . length ) AND ( NOT FOUND )
5 if X = A [ I ] then
6 FOUND = true
7 end if
8 I = I + 1
9 end loop
10 output FOUND
 
4. Computational thinking, problem-solving and programming 122 / 192

Binary Search

Can we do better when the array is sorted?


3 7 8 10 11 15 22
4. Computational thinking, problem-solving and programming 122 / 192

Binary Search

Can we do better when the array is sorted?


3 7 8 10 11 15 22

Assume that we want to search for element X .


1 Let M be the middle element in the array
2 If X = M we stop.
3 If X is smaller than M, then move to first half of the array.
4 If X is greater than M, then move to the second half of the array.
5 Apply repeatedly until the array is exhausted.
The above works since the array is sorted. Otherwise it would not work.
4. Computational thinking, problem-solving and programming 123 / 192

Implementation of Binary Search

 
1 input X
2 FOUND = false
3 START = 0
4 END = A . length - 1
5 loop while ( START <= END ) AND ( NOT FOUND )
6 MID = ( START + END ) div 2
7 if X = A [ MID ] then
8 FOUND = true
9 else if X < A [ MID ] then
10 END = MID - 1
11 else
12 START = MID + 1
13 end if
14 end loop
15 output FOUND
 
4. Computational thinking, problem-solving and programming 124 / 192

Linear (or Sequential) Search is the algorithm that searches for a


given element in a given array by examining all the elements of the
array one by one.
There are no preconditions for using the linear search algorithm: it
can be applied for any element and any array (sorted or unsorted).
It is called linear because, in the worst case, the number of steps
that this algorithm needs is N, where N is the number of elements
in the array.
In the same manner the name sequential describes that the elements
of the array are examined all, one after the other.
 
1 input X
2 FOUND = false
3 loop I from 0 to A . length -1
4 if X = A [ I ] then
5 FOUND = true
6 end if
7 end loop
8 if FOUND then
9 output X , " was found "
10 else
11 output X , " was not found "
12 end if
 
4. Computational thinking, problem-solving and programming 125 / 192

Finding the Positions of Occurrence

Linear search can be used to find the position where an element occurs in
a given array.
 
1 input X
2 FOUND = false
3 loop I from 0 to A . length -1
4 if X = A [ I ] then
5 FOUND = true
6 output X , " was found at position " , I
7 end if
8 end loop
9 if NOT found then
10 output X , " was not found "
11 end if
 
4. Computational thinking, problem-solving and programming 126 / 192

Trace the following algorithm for A the following array and for X = 3.
3 4 3 5 3
 
1 input X
2 FOUND = false
3 loop I from 0 to A . length -1
4 if X = A [ I ] then
5 FOUND = true
6 output X , " was found at position " , I
7 end if
8 end loop
9 if NOT found then
10 output X , " was not found "
11 end if
 
I X = A[I]? FOUND output
false
0 true true 3 was found at position 0
1 false
2 true true 3 was found at position 2
3 false
4 true true 3 was found at position 4
4. Computational thinking, problem-solving and programming 127 / 192

Linear Search (Optimized)


Trace the following algorithm for A the following array and for X = 3.
3 4 3 5 3
 
1 input X
2 FOUND = false
3 I = 0
4 loop while I < A . length AND NOT FOUND
5 if X = A [ I ] then
6 FOUND = true
7 output X , " was found at position " , I
8 end if
9 I = I + 1
10 end loop
11 if NOT found then
12 output X , " was not found "
13 end if
 
I I < A.length AND NOT FOUND X = A[I]? FOUND output
0 true true true 3 was found at position 0
1 false
4. Computational thinking, problem-solving and programming 127 / 192

Linear Search (Optimized)


Trace the following algorithm for A the following array and for X = 3.
3 4 3 5 3
 
1 input X
2 FOUND = false
3 I = 0
4 loop while I < A . length AND NOT FOUND
5 if X = A [ I ] then
6 FOUND = true
7 output X , " was found at position " , I
8 end if
9 I = I + 1
10 end loop
11 if NOT found then
12 output X , " was not found "
13 end if
 
I I < A.length AND NOT FOUND X = A[I]? FOUND output
0 true true true 3 was found at position 0
1 false

What do you observe? If we add NOT FOUND as a condition in the


while loop then we stop at the first occurrence of X.
4. Computational thinking, problem-solving and programming 128 / 192

Binary Search
Binary Search is the algorithm where given a sorted array A an
element X we search whether X occurs in A as follows:
1 Let M be A’s middle element.
2 If X = M then we have succeeded.
3 If X > M then we drop the first half of A (i.e. those elements that
are smaller than X )
4 If X < M then we drop the second half of A (i.e. those elements
that are smaller than X )
5 We repeat from the 1-st step with the new array until either X is
found or the array is exhausted.
In every step of the binary search algorithm we drop half of the
array’s element.
So, each time we divide the number of elements that are going to be
searched by 2.
Therefore the total number of steps performed by binary search is
proportional to log2 N, where N is the number of A’s elements.
Hence, we say that the running time of binary search is logarithmic.
Binary search can only be applied on sorted arrays.
4. Computational thinking, problem-solving and programming 129 / 192

Implementation of Binary Search

 
1 input X
2 FOUND = false
3 START = 0
4 END = A . length - 1
5 loop while ( START <= END ) AND ( NOT FOUND )
6 MID = ( START + END ) div 2
7 if X = A [ MID ] then
8 FOUND = true
9 else if X < A [ MID ] then
10 END = MID - 1
11 else
12 START = MID + 1
13 end if
14 end loop
15 output FOUND
 
4. Computational thinking, problem-solving and programming 130 / 192

Linear Search Binary Search


Linear Search Binary Search
Preconditions None
Array is Sorted
Execution Time Linear Logarithmic
(Number of Steps) (in the worst case (in the worst case
N elements are log2 N elements are
checked) checked)
Efficiency Slower Faster
where N is the number of elements in the array where the search is done.
4. Computational thinking, problem-solving and programming 131 / 192

Sorted Arrays of Strings

Until now we’ve seen arrays that contain only numbers. However, arrays
may contains strings as well.
When we say that an array of strings is sorted we mean that the strings
in the array are sorted alphabetically (or lexicographically).
For example the following array of Strings is sorted lexicographically.

Greg Freedom Jason Liberta Michael Jordan Mike Thanos


4. Computational thinking, problem-solving and programming 132 / 192

Implementation of Binary Search


For A being the following array and for X =Stephen Curry trace the
following algorithm:

Freedom Greg Jason Liberta Michael Jordan Mike Thanos


 
1 input X
2 FOUND = false
3 START = 0
4 END = A . length - 1
5 loop while ( START <= END ) AND ( NOT FOUND )
6 MID = ( START + END ) div 2
7 if X = A [ MID ] then
8 FOUND = true
9 else if X < A [ MID ] then
10 END = MID - 1
11 else
12 START = MID + 1
13 end if
14 end loop
15 output FOUND
 
4. Computational thinking, problem-solving and programming 133 / 192

Freedom Greg Jason Liberta Michael Jordan Mike Thanos

(START<=END) AND (NOT FOUND) MID X = A[MID]? FOUND X < A[MID]? END START
false 6 0
true 3 false false 4
true 5 false false 6
true 6 false true 5
false
4. Computational thinking, problem-solving and programming 134 / 192

Sorting Algorithms

Sorting an array is a fundamental problem in computer science.


For the IB examination you need to know and udnerstand two sorting
algorithms: selection sort and bubblesort.
In the following we always assume that we want to sort the array in
ascending order, unless stated otherwise.
4. Computational thinking, problem-solving and programming 135 / 192

Bubble Sort

Bubble sort is an algorithm that is used to sort an array (of integers


or strings).
The main idea for the bubble sort algorithm is the following:
if two consecutive elements of the array are in the wrong order then
swap them. If no more swaps are necessary then the array is sorted.
So, bubble sort works as follows:
1 Pass all the elements in the array. If elements in consecutive
positions are in the wrong order then swap them. Repeat the passes
until no more swaps are necessary.
2 An array where no more swaps are necessary is sorted. Therefore
bubble sort succeeds in sorting the array.
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1

4 2 5 1 3 0 -1
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1

4 2 5 1 3 0 -1

4 2 1 5 3 0 -1
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1

4 2 5 1 3 0 -1

4 2 1 5 3 0 -1

4 2 1 3 5 0 -1
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1

4 2 5 1 3 0 -1

4 2 1 5 3 0 -1

4 2 1 3 5 0 -1

4 2 1 3 0 5 -1
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1

4 2 5 1 3 0 -1

4 2 1 5 3 0 -1

4 2 1 3 5 0 -1

4 2 1 3 0 5 -1

4 2 1 3 0 -1 5
4. Computational thinking, problem-solving and programming 136 / 192

1st pass

Let A be the following array.


5 4 2 1 3 0 -1

4 5 2 1 3 0 -1

4 2 5 1 3 0 -1

4 2 1 5 3 0 -1

4 2 1 3 5 0 -1

4 2 1 3 0 5 -1

4 2 1 3 0 -1 5

After the first pass the largest element of the array is moved to the last
position of the array (in this case it is 5).
4. Computational thinking, problem-solving and programming 137 / 192

2nd pass

4 2 1 3 0 -1 5
4. Computational thinking, problem-solving and programming 137 / 192

2nd pass

4 2 1 3 0 -1 5

After the second pass the second largest element of the array is moved to
the last position of the array (in this case it is 4).
4. Computational thinking, problem-solving and programming 138 / 192

It is possible that some of the largest elements of an array are already


sorted in the last positions.
4 2 1 3 8 9 10

Then the 1st pass will simply move the 4 before 8, 9 and 10.
4. Computational thinking, problem-solving and programming 139 / 192

Remarks on Bubble Sort

Assume that we want to sort an array of n elements.


Every pass lasts exactly n steps.
After the 1st pass (at least) the largest element is moved to the last
position of the array.
After the 2nd pass (at least) the two largest elements of the array
are sorted in the last positions of the array.
...
After the k-th pass (at least) the k last elements of the array are
sorted.
Hence bubble sort needs at most n − 1 passes.
So, the total number of steps taken by bubble sort are proportional
to n × (n − 1), or as is it usual in computer science, they are
proportional to n2 .
4. Computational thinking, problem-solving and programming 140 / 192

Bubble Sort - Corner Cases

How many steps does bubble sort take when the array is already
sorted?
it takes only one pass, which lasts n − 1 steps
How many steps does bubble sort take when the array is sorted in
reverse (i.e. descending) order? it takes n − 1 passes, which together
last (n − 1) × (n − 1) steps
What is the best case performance of bubble sort? For which kind of
input does it take place?
What is the worst case performance of bubble sort? For which kind f
input does it take place?
4. Computational thinking, problem-solving and programming 141 / 192

Implementation of Bubble Sort

In order to implement bubble sort, we need to learn how to swap


variables . . .
4. Computational thinking, problem-solving and programming 142 / 192

Swapping variables

Let X , Y be variables that contain some data (e.g. integers, strings,


booleans). How can we swap the information held by X and Y ?
4. Computational thinking, problem-solving and programming 142 / 192

Swapping variables

Let X , Y be variables that contain some data (e.g. integers, strings,


booleans). How can we swap the information held by X and Y ?
X and Y can be understood as boxes. How is it possible to move the
contents of box X to box Y and vice versa?
 
1 X = 5
2 Y = 7
3 X = Y
4 Y = X
 
The above code does not work! Find out why!
4. Computational thinking, problem-solving and programming 143 / 192

Swapping variables

Solution: We need a third box, called TEMP


 
1 X = 5
2 Y = 7
3 TEMP = X // we store X ’ s last value
4 X = Y
5 Y = TEMP
 
4. Computational thinking, problem-solving and programming 144 / 192

Swapping Array Elements

Elements of arrays may also be swapped. Let A be the following array:


5 4 2 1 3 0 -1

The following code swaps elements A[0] and A[3]


 
1 TEMP = A [3]
2 A [3] = A [0]
3 A [0] = TEMP
 
After the above code, A looks like:
1 4 2 5 3 0 -1
4. Computational thinking, problem-solving and programming 145 / 192

Implementation of Bubble Sort

Let A be the array that needs to be sorted.


 
1 SWAP = true // we set SWAP = true , so that while loop starts
2 loop while SWAP // loop while SWAP = TRUE
3 SWAP = false
4 loop I from 0 to A . length -2
5 if A [ I ] > A [ I +1] then
6 TEMP = A [ I ] // we swap A [ I ] and A [ I +1]
7 A [ I ] = A [ I +1]
8 A [ I +1] = TEMP
9 SWAP = true
10 end if
11 end loop
12 end loop
 
4. Computational thinking, problem-solving and programming 146 / 192

Selection Sort

Selection sort is another algorithm that is used to sort linear arrays1


The idea of the selection sort algorithm is the following:
assume that we need to sort an array A of N elements
find the minimum element of the array and swap it with A[0]
then find the minimum among the elements A[1], . . . , A[N − 1] and
swap it with A[1].
then find the minimum among the elements A[2], . . . , A[N − 1] and
swap it with A[2].
...
So the idea in selection sort is that we always bring the minimum to
the front and continue like that until the array is sorted.

1 Anarray is called linear if it has only 1 dimension. All the arrays you see in the SL
are linear.
4. Computational thinking, problem-solving and programming 147 / 192

Example of Selection Sort

5 4 2 -1 0 3

-1 4 2 5 0 3

-1 0 2 5 4 3

-1 0 2 5 4 3

-1 0 2 3 4 5
4. Computational thinking, problem-solving and programming 148 / 192

Selection

This video explains the selection sort algorithm nicely:


https://youtu.be/f8hXR_Hvybo
In selection sort the array is divided in two lists: the list of unsorted
elements which is in the beginning of the array and the list of the
sorted elements which is at the end of the array.
Initially the list of sorted elements is empty and the list of unsorted
elements consists of all the elements in the array.
Each time we find the minimum element of the unsorted list and we
put it at the end of the sorted list.
This way the sorted list always grows larger and the unsorted list
always grows smaller.
Finally the sorted list will contain the whole array.
4. Computational thinking, problem-solving and programming 149 / 192

Example of Selection Sort

Unsorted
8 2 -2 0 3 4

Sorted Unsorted
-2 2 8 0 3 4

Sorted Unsorted
-2 0 8 2 3 4

Sorted Unsorted
-2 0 2 8 3 4

Sorted Unsorted
-2 0 2 3 8 4

Sorted
-2 0 2 3 4 8
4. Computational thinking, problem-solving and programming 150 / 192

Finding the Minimum of An array

 
1 min = A [0]
2 loop I from 1 to A . length - 1
3 if A [ I ] < min then
4 min = A [ I ]
5 end if
6 end loop
7 output min
 
 
1 min = 0
2 loop I from 1 to A . length - 1
3 if A [ I ] < min then
4 min = I
5 end if
6 end loop
7 output A [ min ]
 
How many comparisons does it take?
4. Computational thinking, problem-solving and programming 151 / 192

Swap Two Elements in the Array

 
1 TEMP = A [ i ]
2 A[i] = A[j]
3 A [ j ] = TEMP
 
4. Computational thinking, problem-solving and programming 152 / 192

Selection Sort - Implementation

 
1 loop I from 0 to A . length - 2
2 MIN = I
3 loop J from I +1 to A . length -1
4 if A [ J ] < A [ I ] then
5 MIN = J
6 end if
7 end loop
8 TEMP = A [ I ]
9 A [ I ] = A [ MIN ]
10 A [ MIN ] = TEMP
11 end loop
 
Lines 2 to 7 find the minimum element among the elements A[I] to
A[A.length-1].
Lines 8 to 10 swaps elements A[I] and A[MIN].
4. Computational thinking, problem-solving and programming 153 / 192

Selection Sort - Complexity

The initial unsorted list contains n elements. So it takes n − 1


comparisons to find the minimum.
The next unsorted list contains n − 1 elements. So it takes n − 2
comparisons to find the minimum.
...
The final unsorted list contains 2 elements. So it takes 1 comparison
to find the minimum.
In total it takes
n(n − 1)
n − 1 + n − 2 + ... + 2 + 1 =
2
comparisons
4. Computational thinking, problem-solving and programming 154 / 192

Big O notation

In the analysis of algorithms we care about the behavior of


algorithms for large inputs.
Therefore if an algorithm takes 5 · n2 + n steps we say that it takes
O(n2 ) steps.
If an algorithm takes 5 · n3 + 6 · n2 steps we say that it takes O(n3 )
steps.
In general, in a polynomial we care only about the term with the
highest exponent and we forget the coefficients.
4. Computational thinking, problem-solving and programming 155 / 192

Selection Sort - Complexity


Assume that the array contains n elements
Is there a best case for selection sort?
in terms of comparisons there is no best case, but in terms of swaps
the best case is when the array is sorted
Is there a worst case for selection sort?
in terms of comparisons there is no best case, but in terms of swaps
the best case is when the array is inversely sorted
How many swaps are needed in the worst case?
O(n)
How many swaps are needed in the best case?
no swaps
How many comparisons are needed in the worst case?
O(n2 )
How many comparisons are needed in the best case?
O(n2 )
4. Computational thinking, problem-solving and programming 155 / 192

Selection Sort - Complexity


Assume that the array contains n elements
Is there a best case for selection sort?
in terms of comparisons there is no best case, but in terms of swaps
the best case is when the array is sorted
Is there a worst case for selection sort?
in terms of comparisons there is no best case, but in terms of swaps
the best case is when the array is inversely sorted
How many swaps are needed in the worst case?
O(n)
How many swaps are needed in the best case?
no swaps
How many comparisons are needed in the worst case?
O(n2 )
How many comparisons are needed in the best case?
O(n2 )
Selection sort always makes the same number of comparisons. However,
if the array “looks sorted” it will make few swaps.
4. Computational thinking, problem-solving and programming 156 / 192

Bubble Sort Selection Sort


Bubble Sort Selection Sort
Best Case no swaps and n − 1 no swaps and O(n2 )
comparisons comparisons
Worst Case O(n2 ) swaps and O(n) swaps and
O(n2 ) comparisons O(n2 ) comparisons

The conclusion is that bubblesort usually makes a lot of swaps and


selection sort always makes a lot of comparisons but not so many swaps.
If you are lucky bubblesort finishes relatively fast (i.e. in one pass).
However selection sort cannot finish that fast. It has to bring all the
minimum elements in the front even if the array is already sorted.
4. Computational thinking, problem-solving and programming 157 / 192

Bubble Sort vs Selection Sort (Which should I use?)

You should use selection sort when you want to make fewer swaps.
You should use bubble sort when you hope that the array is almost
sorted, so you can finish faster.
You should use selection sort when you want that the smallest
elements appear in the beginning of the array very fast.
You should use bubble sort when you want that the largest elements
appear at the end of the array very fast.
However nowadays both algorithms are considered extremely
inefficient and are almost never used in practice.
4. Computational thinking, problem-solving and programming 158 / 192

Trace the following algorithm:


 
1 loop K from 1 to 3
2 loop J from 1 to 3
3 if J <= K then
4 output " * "
5 end if
6 end loop
7 end loop
 
How many times is the comparison J<=K executed?
How many times is the command output "*" executed?
4. Computational thinking, problem-solving and programming 159 / 192

Let A be an array. What is the mistake in the following algorithm? How


can it be fixed?
 
1 loop I from 0 to A . length
2 output A [ I ]
3 end loop
 
4. Computational thinking, problem-solving and programming 160 / 192

Array Minimum

Let A be an array of integers, Write an algorithm that outputs the


minimum element of A.
 
1 MIN = A [0]
2 loop I from 1 to A . length - 1
3 if A [ I ] < MIN then
4 MIN = A [ I ]
5 end if
6 end loop
7 output MIN
 
4. Computational thinking, problem-solving and programming 161 / 192

Let CS be an array that contains the name of 20 students that have


selected computer science and let M be an array that contains the names
of 15 students that have selected mathematics.
Write an algorithm that transfers all the common names in arrays CS and
M to an array called Common.
 
1 C = 0
2 loop I from 0 to 19
3 loop I from 0 to 14
4 if CS [ I ] = M [ J ]
5 COMMON [ X ] = CS [ I ]
6 X = X + 1
7 end if
8 end loop
9 end loop
 
Array Common will contain at most 15 elements.
4. Computational thinking, problem-solving and programming 162 / 192

Algorithm Flowcharts

An algorithm can also be represented as a flowchart, using the following


notation.

input or output

condition check
(if N > 0 then ... else)

calculation
4. Computational thinking, problem-solving and programming 163 / 192

While Loop Flowchart

loop while condition


commands
end loop
4. Computational thinking, problem-solving and programming 164 / 192

From pseudocode to flowchart

Convert the following algorithm to flowchart.


 
1 input A
2 input B
3 N = A div B
4 loop I from 0 to A mod B
5 output N
6 N = N - 1
7 end loop
8 if N < -3 then
9 output " perfect "
10 else
11 output " not perfect "
12 end if
 
4. Computational thinking, problem-solving and programming 165 / 192

Algorithm to reverse an array

Construct an algorithm that will reverse an array called A.


For example if the array A looks like this
1 2 -1 5 3

after the algorithm it should look like this:


3 5 -1 2 1
4. Computational thinking, problem-solving and programming 166 / 192

Consider the following array, called NAMES


Robert Boris Brad George David

and the following algorithm, which is constructed to reverse the contents


of the array NAMES.
 
1 N = 5 // the number of elements in the array
2 K = 0 // this is the first index in the array
3 loop while K < N - 1
4 TEMP = NAMES [ K ]
5 NAMES [ K ] = NAMES [ N - K - 1]
6 NAMES [ N - K - 1] = TEMP
7 K = K + 1
8 end loop
 
1 Trace the algorithm, showing the contents of the array after each
execution of the loop.
2 Identify the type of error that occurs.
3 Outline why the error occurs and how it could be corrected.
4. Computational thinking, problem-solving and programming 167 / 192

Object Oriented Programming

In object oriented programming (OOP) we have the following basic


concepts:
Classes: Abstract entities that describe general features of
“objects” (e.g. a class car, a class dog)
Objects: “Real” entities that are instantiations of classes (e.g. a
specific dog, a specific car).
In OOP classes and therefore also objects may have properties or
attributes and can change their state using functions.
E.g. a car could have the property “color”, or “size” and the function
“drive()” or “park()”. A dog could have the property “color” or “breed”
and the functions “eat()” and “run()”.
The functions that an object or a class may have are called methods.
So, a method is a way of accessing or modifying an object.
4. Computational thinking, problem-solving and programming 168 / 192

Class Car and Relative Objects


4. Computational thinking, problem-solving and programming 169 / 192

Class Dog and Relative Objects


4. Computational thinking, problem-solving and programming 170 / 192

For example assume that we have a printer named P. This printer could
be understood as an object and could have the following methods.
print() this method makes the printer print
hasInk() this method checks whether the printer has ink
hasPaper() this method checks whether the printer has paper
The parentheses after the method denote that it takes no arguments.
We can force the printer to print, with the following command: P.print().
We can check whether P has ink by writing P.hasInk() = true.
4. Computational thinking, problem-solving and programming 171 / 192

The methods of the printer P are called using the . and the name of the
method.
The following algorithm checks whether the printer has ink and paper
and then asks the printer to print.
 
1 if P . hasInk () = true AND P . hasPaper () = true then
2 P . print ()
3 end if
 
4. Computational thinking, problem-solving and programming 171 / 192

The methods of the printer P are called using the . and the name of the
method.
The following algorithm checks whether the printer has ink and paper
and then asks the printer to print.
 
1 if P . hasInk () = true AND P . hasPaper () = true then
2 P . print ()
3 end if
 
Since the methods P.hasInk() and P.hasPaper() return boolean values
(that is true or false) we could equivalently write the following
 
1 if P . hasInk () AND P . hasPaper () then
2 P . print ()
3 end if
 
The printer could also have an attribute color, which is accessed as
P.color.
4. Computational thinking, problem-solving and programming 172 / 192

Let A be an array. One property of A is its length which is denoted as


A.length.
The array could also have a method called print() which is
implemented as follows:
4. Computational thinking, problem-solving and programming 172 / 192

Let A be an array. One property of A is its length which is denoted as


A.length.
The array could also have a method called print() which is
implemented as follows:
 
1 print ()
2 loop I from 0 to A . length -1
3 output A [ I ]
4 end loop
5 end print
 
4. Computational thinking, problem-solving and programming 173 / 192

The array could also have a property called linearSearch which is


implemented as follows:
4. Computational thinking, problem-solving and programming 173 / 192

The array could also have a property called linearSearch which is


implemented as follows:
 
1 linearSearch ( X )
2 found = false
3 loop I from 0 to A . length -1
4 if X = A [ I ] then
5 found = true
6 end if
7 end loop
8 return found
9 end print
 
4. Computational thinking, problem-solving and programming 173 / 192

The array could also have a property called linearSearch which is


implemented as follows:
 
1 linearSearch ( X )
2 found = false
3 loop I from 0 to A . length -1
4 if X = A [ I ] then
5 found = true
6 end if
7 end loop
8 return found
9 end print
 
The X in linearSearch(X) is called the argument or parameter of the
method linearSearch and it is the value we are going to search for in
the array A.
The previous methods are called as A.print() and A.linearSearch(X)
respectively.
4. Computational thinking, problem-solving and programming 174 / 192

The method linearSearch can also be implemented without using a


boolean variable as follows:
4. Computational thinking, problem-solving and programming 174 / 192

The method linearSearch can also be implemented without using a


boolean variable as follows:
 
1 linearSearch ( X )
2 loop I from 0 to A . length -1
3 if X = A [ I ] then
4 return true
5 end if
6 end loop
7 return false
8 end print
 
4. Computational thinking, problem-solving and programming 175 / 192

Data Structure
A data structure is a way of organizing (i.e. storing) data (i.e.
information).
In a data structure, data are organized in a form such that several factors
are optimized: e.g. search time, insertion/deletion time, storage space,
etc.
Examples of data structures are arrays and collections
4. Computational thinking, problem-solving and programming 176 / 192

Static vs. Dynamic Data Structure

Static Data Structure


A static data structure has fixed size and shape.
Example of a static data structure is an array.

Dynamic Data Structure


A dynamic data structure has non-fixed size and shape.
Example of a dynamic data structure is a collection.

Usually dynamic data structures are used in order to save space and
optimize search algorithms.
Static data structures are typically used in order to have fast (random)
access of elements and simplify implementation.
4. Computational thinking, problem-solving and programming 177 / 192

Collection

A collection is a dynamic data structure that “behaves like” a set in


Mathematics.
It does not have fixed length and data can be inserted to them.
A collection can be empty and can grow indefinitely.
Collections are usually represented as {5, 4, 11, −5}.
Collections are treated as objects which have the following basic
methods:
addItem(X): inserts the item X at the end of the collection
resetNext(): puts a scanning pointer at the first element of the
collection
hasNext(): checks whether the pointer of the collection has not
reached the end of the collection
getNext(): returns the element where the pointer of the collection
is pointing at
4. Computational thinking, problem-solving and programming 178 / 192

From Array to Collection

The following code copies all elements of an array named A to a


collection named C .
4. Computational thinking, problem-solving and programming 178 / 192

From Array to Collection

The following code copies all elements of an array named A to a


collection named C .
 
1 loop I from 0 to A . length -1
2 C . addItem ( A [ I ])
3 end loop
 
4. Computational thinking, problem-solving and programming 179 / 192

From Input to Collection

The following code reads 20 integers from input and puts them in a
collection named C .
4. Computational thinking, problem-solving and programming 179 / 192

From Input to Collection

The following code reads 20 integers from input and puts them in a
collection named C .
 
1 loop I from 1 to 20
2 input X
3 C . addItem ( X )
4 end loop
 
4. Computational thinking, problem-solving and programming 180 / 192

Accessing Data of a Collection

Let C = {3,5,-11,80, 97} be a collection. The following code prints


all the elements of the collection C.
4. Computational thinking, problem-solving and programming 180 / 192

Accessing Data of a Collection

Let C = {3,5,-11,80, 97} be a collection. The following code prints


all the elements of the collection C.
 
1 C . resetNext ()
2 loop while C . hasNext ()
3 output C . getNext ()
4 end loop
 
4. Computational thinking, problem-solving and programming 180 / 192

Accessing Data of a Collection

Let C = {3,5,-11,80, 97} be a collection. The following code prints


all the elements of the collection C.
 
1 C . resetNext ()
2 loop while C . hasNext ()
3 output C . getNext ()
4 end loop
 
The 3 methods C.resetNext(), C.hasNext() and C.getNext() should
always be used as above in order to access all the data of a collection.
You can imagine that C.resetNext() puts a pointer at the first
element of C
C.hasNext() checks whether the pointer is pointing to an element
of C
C.getNext() fetches the element where the pointer is pointing at
4. Computational thinking, problem-solving and programming 181 / 192

Copy to Collection

Let B, C be collections. Assume that B contains some elements and that


C is initially empty.
Write an algorithm that copies all the elements of B to C .
4. Computational thinking, problem-solving and programming 181 / 192

Copy to Collection

Let B, C be collections. Assume that B contains some elements and that


C is initially empty.
Write an algorithm that copies all the elements of B to C .
 
1 B . resetNext ()
2 loop while B . hasNext ()
3 C . addItem ( C . getNext () )
4 end loop
 
4. Computational thinking, problem-solving and programming 182 / 192

Search in a Collection

Let B be a collection.
Write an algorithm that searches for element X in collection B.
4. Computational thinking, problem-solving and programming 182 / 192

Search in a Collection

Let B be a collection.
Write an algorithm that searches for element X in collection B.
 
1 found = false
2 B . resetNext ()
3 loop while B . hasNext ()
4 if X = B . getNext () then
5 found = true
6 end if
7 end loop
8 if found then
9 output X , " was found "
10 else
11 output X , " was not found "
12 end if
 
4. Computational thinking, problem-solving and programming 183 / 192

Search in a Collection

Let B be a collection and assume that element X may appear at most


once in B.
Write an efficient algorithm that searches for element X in collection B.
4. Computational thinking, problem-solving and programming 183 / 192

Search in a Collection

Let B be a collection and assume that element X may appear at most


once in B.
Write an efficient algorithm that searches for element X in collection B.
 
1 found = false
2 B . resetNext ()
3 loop while B . hasNext () and not found
4 if X = B . getNext () then
5 found = true
6 end if
7 end loop
8 if found then
9 output X , " was found "
10 else
11 output X , " was not found "
12 end if
 
4. Computational thinking, problem-solving and programming 184 / 192

Search in a Collection

Let C be a collection and A be an array.


Write an algorithm that prints all the common elements found in A and
C . If A and C have no common elements the algorithm should print an
appropriate message.
4. Computational thinking, problem-solving and programming 184 / 192

Search in a Collection

Let C be a collection and A be an array.


Write an algorithm that prints all the common elements found in A and
C . If A and C have no common elements the algorithm should print an
appropriate message.
 
1 common = false
2 C . resetNext ()
3 loop while C . hasNext ()
4 loop I from 0 to A . length -1
5 if C . getNext () = A [ I ] then
6 output A [ I ]
7 common = true
8 end if
9 end loop
10 end loop
11 if NOT common then
12 output " No common elements "
13 end if
 
4. Computational thinking, problem-solving and programming 185 / 192

Example

Write a method count that takes a collection as input and returns the
number of elements in the collection.
4. Computational thinking, problem-solving and programming 186 / 192

Example

The of students who play football are stored in an array F. The names of
students who play basketball are stored in a collection named B.
1 Write a method S that takes as input a name N and an array A and
returns true if S appears in A and false otherwise.
2 Use the method from the previous subquestion to count the number
of students that play both football and basketball.
4. Computational thinking, problem-solving and programming 187 / 192

Fundamental Operations of a Computer

All CPUs have sets of instructions, also called the fundamental


operations that enable commands to be processed.
The four fundamental operations are:
ADD
COMPARE
RETRIEVE (sometimes called LOAD)
STORE (sometimes called SAVE)
4. Computational thinking, problem-solving and programming 188 / 192

Example

Assume that number A is stored at memory location 40 and number


B is stored at memory location 50
Using the operation RETRIEVE the computer can transfer numbers
A and B from RAM to CPU
Then it can add A and B and STORE the result to memory location
60.
Similarly it could compare A and B and store the result (as a
boolean value) in memory location 80.
4. Computational thinking, problem-solving and programming 189 / 192

Fundamental vs compound operations

A fundamental operation could be something like add two numbers,


store a number, move a number to another location in RAM etc.
These are operations that do not require the processor to go through
a large number of sub operations to reach a result.
A compound operation is an operation that involves a number of
stages/other operations. Think of it as a group of operations that
combine together to form an operation.
By combining fundamental computer operations, computers can
perform compound operations.
For example, finding the maximum value of four numbers is a
compound operation.
4. Computational thinking, problem-solving and programming 190 / 192

Programming

Programming involves the creation of a series of steps that will solve


a problem.
Programming is a process of solving a problem in phases. A
computer program is a sequence of instructions that “explains” to
the computer how to solve a specific problem.Essential Features of a
4. Computational thinking, problem-solving and programming 191 / 192

Programming/Computer Language

A programming language is described as a combination of:


Semantics, which refers to the meaning of every construction that is
possible in the language.
Syntax, which refers to its structure.
Grammar is a meta-language that is used to define the syntax of a
language, while the rules of statement construction are called syntax.
Each higher level language has a unique syntax and a specific limited
vocabulary.
A command written in a computer language always means the same
and there is no ambiguity of meaning.
4. Computational thinking, problem-solving and programming 192 / 192

Fixed vocabulary, unambiguous meaning, consistent


grammar and syntax

fixed vocabulary set, unchanging (There are only around 50 reserved


words in Java, though a bunch more class names like
System which are already taken)
unambiguous meaning - can only be interpreted one way
consistent grammar - the order of words. Grammar is a much bigger
concept. It is the set of all rules which a program needs to
obey.
syntax basically spelling and punctuation. Programming syntax
contains strings similar to words, much like a human
language. Correctly formed syntax strings produce
syntactically correct sentences within a specified
programming language.

You might also like