Algorithms
Algorithms
Programming
Algorithms development
1
Problem solving
Solving a problem on the computer
involves
• defining a problem
• Analysing a problem
• Developing an algorithm
• Writing the computer program
• Testing and debugging
• Documenting the program
4
Problem analysis
• Analyse the problem to make sure that you
understand it.
• Determine the general requirements of the
problem (inputs, output and files for more
complicated problems)
• The main analysis here is to find how to
convert the given temperature.
If the given temperature is C, then the
converted temperature F, is given by
F = 32 + (9C / 5)
5
• C and F are called variables
• When data is entered, it is stored in a
memory.
• Each memory location can hold 1 data
item.
• Variable is the name associated with a
memory location.
• We can give a variable an value e.g.
when entering centigrade OR setting a
variable to a specific value.
6
Algorithm
• Ask the user for the Centigrade
temperature
• Store the value in C
• Calculate the corresponding Fahrenheit
temperature
• Store it in F
• Print the values in boxes C and F,
appropriately labeled.
• Stop
7
Test an algorithm
• The algorithm must be checked to make
sure that it is doing its job correctly.
• Executing the instructions by hand,
using the appropriate values is called
dry running or desk checking.
8
Simplify algorithm
Simplify the algorithm by combining step 2
and step 3, assuming we know the
formula
• Prompt the user for the Centigrade
temperature
• Store the value in C
• Set F to 32 + (9C/5)
• Print C and F, appropriately labeled
• Stop
9
Exercise
Write algorithm for
• A program that calculates the
percentage mark for a student
• Write a program that calculates the
average mark of a student in 4 subjects
• A program that calculates and prints
powers of 2 up to 32.
10
LOOPING
11
• E.g.
• Prompt the user for the Centigrade
temperature.
• Store the value in C
• Set F to 32+(9C/5).
• Print C and F, appropriately labelled.
• Go to step 1.
• Now instead of stopping at step 5, the
algorithm transfers the control to step 1,
causing it to repeat.
12
How do we get the algorithm to
stop?
• Since the user is now doing as many
calculations as he can, it is up to him to tell
the program to stop.
• He only talks to the program when he enters
the centigrade temperature.
• This is where he can tell the program to stop.
• The particular number can be chosen that
will stop the program when entered.
• Since the program can not be used to give
the Fahrenheit equivalent to 0 Centigrade, 0
can be used to terminate the program.
• Then the If- Then loop can be used.
13
The If- Then- Else and the Top Down
Design
The algorithm may now look like this:
• Prompt user for the Centigrade temperature.
• Store the value in C
• If C = 0 then stop.
• Set F to 32+(9C/5).
• Print C and F, appropriately labelled.
• Go to step 1.
16
• A psedocode for our previous problem
will look like this:
• Get a value for C. As long as C is not
zero, convert C and get another value
for C. When C is zero, stop.
It is usual when writing pseudocode to
use statements similar to statements in
high-level languages and it helps when
it is converted to a computer program.
17
• When writing psedocode, we can use a
number of constructs.
• Constructs reflect the kind of processing
which is usually needed in most
computer programs.
• The commonly used constructs specify:
• Repetition (instructions are to be
repeated under certain conditions)
• Selection (choosing a specified group of
instructions for execution):
18
WHILE Construct
• We can re-write the algorithm from the
previous psedocode, using the WHILE
Construct.
• Prompt the user for Centigrade temperature,
C
• WHILE C is not 0 DO
• Set F to 32+(9C/5)
• Print C and F, appropriately labelled
• Prompt the user for a Centigrade
temperature, C
• END WHILE
• STOP 19
• A WHILE construct (WHILE loop)
consists of
• The word WHILE
• A condition
• The word DO
• One or more statements
• The word ENDWHILE, indicating the
end of the loop.
20
• When the loop is encountered
• The condition is tested
• If it is true the statements in the loop are
executed and then the process is
repeated
• If the condition is false, the loop
terminates or we exit the loop.
• Then execution continues at the
statements following the ENDWHILE
21
• A statement inside the loop that
changes the value of C is important
because, if C is not change inside the
loop, and if the condition is true and the
loop is entered, it will remain true
forever and the loop never terminate.
• If C is 0 the first time, the loop is exited
immediately.
22
Structured Programming
• It can give higher productivity and
produce programs of high quality which
are easy to test, debug, modify and
maintain.
It emphasises:
• Modular development; large problem is
divided into smaller subproblems and if
necessary subproblems are further
subdivided. A module is developed for
each subproblem, performing a single
specific task.
23
• The use of a few simple control
structures in specifying algorithm.
These structures remove the need for
GOTO statements in the program
because to many of them make the
program difficult to read and modify.
24
IF…THEN…ELSE Construct
• Usually referred to as the selection construct,
since for any given test of the condition, one
set of statements is selected for execution.
• It consists of
the word IF
A condition
The word THEN
One/more statements called ‘the THEN part’
The word ELSE
One/more statements called ‘the ELSE part’
The word ENDIF, indicating the end of the
construct 25
Problem
• Derive the algorithm which asks the
user for 2 numbers, A and B, and
calculates the value of A divided by B.
• However if B is 0, a message is printed
which says that division by 0 is not
allowed.
26
Algorithm
• Prompt the user for 2 numbers, A and B
IF B = 0 THEN
Print (“division by 0 is not allowed)
ELSE
set C to A/B
Print A, B and C appropriately
labeled
ENDIF
STOP
27
Execution
• The construct is tested
• If it is true, the THEN part is executed,
and execution continues with the
statement following ENDIF, the ELSE
part is skipped.
• If the condition is false, the ELSE part is
executed, and execution continues with
the statement following ENDIF, the
THEN part is skipped.
28
E.G.
• Suppose the user enters the numbers
20 and 5.
• A 20 B5
• The algorithm tests if B=0; since is not0,
the condition is false. Therefore ELSE
part is executed.
• A is divided by B and the result is stored
in C.
• The result is printed.
29
E.G.
• But suppose the user enters the
numbers 1 and 0.
• A 1 B 0
32
Analysis
• Suppose the user enters 18. since it is the
first, it is the largest so far.
• Then she enters 15. it is ignored and 18 is
held.
• Then she enters 25. 18 is dropped and 25 is
held since is larger than 18.
• The user goes on entering positive numbers
until she enters 0 to indicate the end of data.
• Then the largest number that is held is
printed.
33
Algorithm
• Prompt the user for a number, largest
• Prompt the user for a number new
• WHILE new ≠ 0 DO
IF new > largest THEN
set largest to new
ENDIF
prompt the user for a number, new
ENDWHILE
Print (“the largest number is”, largest)
STOP
34
• Note that , if new is greater than largest,
we want to update largest to this new,
but if it is not greater, we want to do
nothing; thus the IF statement has no
ELSE part.
35
The REPEAT …UNTIL construct
It consists of
• The word REPEAT
• One or more statements, forming the
body of the repeat loop
• The word UNTIL
• A condition
36
REPEAT …UNTIL cont…
• When it is encountered, the following
actions take place:
1. The body of the loop is executed
2. The condition is tested
3. If it is false, we repeat the process from 1.
4. if the condition is true, we exit the
structure, and resume execution at the
statement following the condition.
• So as long as the condition is false, the
loop is repeated. When it becomes true,
execution of the loop is stopped.
37
Problem
• A man deposits $1000 in a bank at an
interest rate of 10% per year. At the end of
each year, the interest earned is added to
the amount on deposit and this becomes the
new deposit for the next year. Develop an
algorithm to determine the year in which the
amount accumulated first exceeds $2000.
Also, for each year, print the year (starting
from 1), the deposit, the interest earned and
the total accumulated at the end of the year.
38
Analysis
Year Deposit Interest Total
1 1000.00 100.00 1100.00
2 1100.00 110.00 1210.00
3 1210.00 121.00 1331.00
4 1331.00 133.10 1464.10
5 1464.10 146.41 1610.51
6 1610.51 161.05 1771.56
7 1771.56 177.16 1948.72
8 1948.72 194.87 2143.59
39
• It is very important to understand the
problem and the way it will be solved by
hand.
• From the above, it appears we will need
4 variables to hold 4 quantities printed
on each line.
40
• Year will be initialised to 0
• Deposit must be set to 1000
• Interest and Total will have to be
calculated; they don’t need to be
initialised.
The main processing would be:
• Calculate Interest
• Calculate Total
• Print Year, Deposit, Interest, Total
• Set Deposit to Total
• This is repeated until Deposit is greater
than 2000.
41
Algorithm
• Set Deposit to 1000
• Print heading “YEAR DEPOSITE INTEREST TOTAL”
• Set Year to 0
• REPEAT
• Add 1 to Year
• Set Interest to 10% of Deposit, that is,
Deposit*0.1
• Set Total to Deposit + Interest
• Print (Year, Deposit, Interest, Total)
• Set deposit to Total [the new deposit for next
year]
• UNTIL Deposit > 2000
• Print (“The total first exceeds $2000 at the end of year”,
Year )
• Print (“the amount is”, Deposit) 42
• STOP
Exercises
What will the output be?
1.
• Set n to 7
• REPEAT
• Print (n)
• Set n to (n - 5)
• Print (“ hi ”, n )
• UNTIL n < 0
• STOP
43
2.
Show a trace table.
• Set n to 1
• Set sum to 0
• REPEAT
• Set sum to sum + (n * n)
• Set n to (n + 2)
• UNTIL n > 7
• Print (“sum = ”, sum)
• STOP
44
Error in writing code
47
• If we were to write the above algorithm having a
logic error, it may look like this:
• Set n to 1
• Set sum to 0
• REPEAT
• Set sum to sum + (n * n)
• Set n to (n * 2)
• UNTIL n > 7
• Print (“sum = ”, sum)
• STOP
• This program will be executed but the results
will not be what was expected.
• The program may end pre- maturely.
• This means that neither the compiler nor the
48
interpreter will not detect this kind of error.