Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Algorithm

◼ Introduction
What is an algorithm?
◼ An algorithm is “a finite set of precise
instructions for performing a computation or for
solving a problem”
 A program is one type of algorithm
◼ All programs are algorithms
◼ Not all algorithms are programs!
 Directions to somebody’s house is an algorithm
 A recipe for cooking a cake is an algorithm
 The steps to compute the cosine of 90° is an
algorithm
2
Algorithms
◼ A tool for solving a well-specified
computational problem

Input Algorithm Output

◼ Algorithms must be:


 Correct: For each input produce an appropriate output
 Efficient: run as quickly as possible, and use as little
memory as possible – more about this later

3
Algorithms Cont.
◼ A well-defined computational procedure that
takes some value, or set of values, as input and
produces some value, or set of values, as
output.

◼ Written in a pseudo code which can be


implemented in the language of programmer’s
choice.
4
Correct and incorrect algorithms
◼ Algorithm is correct if, for every input instance, it ends
with the correct output. We say that a correct algorithm
solves the given computational problem.

◼ An incorrect algorithm might not end at all on some input


instances, or it might end with an answer other than the
desired one.

◼ We shall be concerned only with correct algorithms.

5
ALGORITHMS

◼ Is the series of steps that are used to solve a


programming problem
◼ a plan for solving a programming problem that
specifies the sequence of steps used in the
solution.
◼ 1. An algorithm must have a start and an end
point.
◼ 2. Every step must be doable or performable:-
(a) using a finite amount of effort;
 (b) in a finite amount of time.
Problems and Algorithms
◼ We need to solve a computational problem
 “Convert a weight in pounds to Kg”

◼ An algorithm specifies how to solve it, e.g.:


 1. Read weight-in-pounds
 2. Calculate weight-in-Kg = weight-in-pounds
* 0.455
 3. Print weight-in-Kg

◼ A computer program is a computer-


7
executable description of an algorithm
The Problem-solving Process
Analysis
Problem
specification
Design

Algorithm
Implementation
Program

Compilation
Executable
(solution)
8
From Algorithms to Programs
Problem
Algorithm: A sequence
of instructions describing
how to do a task (or
process)

C++ Program
9
Practical Examples
◼ Internet and Networks
􀂄 The need to access large amount of information with the
shortest time.
􀂄 Problems of finding the best routs for the data to travel.
􀂄 Algorithms for searching this large amount of data to quickly
find the pages on which particular information resides.

◼ Electronic Commerce
􀂄 The ability of keeping the information (credit card numbers,
passwords, bank statements) private, safe, and secure.
􀂄 Algorithms involves encryption/decryption techniques.
10
Hard problems
◼ We can identify the Efficiency of an algorithm
from its speed (how long does the algorithm
take to produce the result).
◼ Some problems have unknown efficient
solution.
◼ These problems are called NP-complete
problems.
◼ If we can show that the problem is NP-
complete, we can spend our time developing
11an efficient algorithm that gives a good, but
Components of an Algorithm
◼ Variables and values(data structure)
◼ Instructions
◼ Sequences
 A series of instructions
◼ Procedures
 A named sequence of instructions
 we also use the following words to refer to a
“Procedure” :
◼ Sub-routine
◼ Module

◼ Function
12
Components of an Algorithm
Cont.
◼ Selections(if and if else..)
 An instruction that decides which of two
possible sequences is executed
 The decision is based on true/false condition

◼ Repetitions(for, while and do while loop)


 Also known as iteration or loop
◼ Documentation
 Records what the algorithm does
13
A Simple Algorithm
◼ INPUT: a sequence of n numbers
 T is an array of n elements
 T[1], T[2], …, T[n]
◼ OUTPUT:min
the= smallest
T[1]
number among them
for i = 2 to n do
{
if T[i] < min
min = T[i]
}
Output min


14
Performance of this algorithm is a function of n
ALGORITHMS AND
FLOWCHARTS

Problem Analysis
ALGORITHMS AND FLOWCHARTS
◼ A typical programming task can be divided into
two phases:
◼ Problem solving phase
 produce an ordered sequence of steps that describe
solution of problem
 this sequence of steps is called an algorithm

◼ Implementation phase
 implement the program in some programming
language
Steps in Problem Solving
◼ First produce a general algorithm (one can use
pseudocode)
◼ Refine the algorithm successively to get step by
step detailed algorithm that is very close to a
computer language.
◼ Pseudocode is an artificial and informal
language that helps programmers develop
algorithms. Pseudocode is very similar to
everyday English.
Pseudocode & Algorithm
◼ Example 1: Write an algorithm to
determine a student’s final grade and
indicate whether it is passing or failing.
The final grade is calculated as the
average of four marks.
Pseudocode & Algorithm
Pseudocode:
◼ Input a set of 4 marks
◼ Calculate their average by summing and dividing
by 4
◼ if average is below 50
Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm
◼ Detailed Algorithm
◼ Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart
◼ (Dictionary) A schematic representation of a sequence of
operations, as in a manufacturing process or computer
program.
◼ (Technical) A graphical representation of the sequence of
operations in an information system or program.
 Information system flowcharts show how data flows from source
documents through the computer to final distribution to users.
 Program flowcharts show the sequence of instructions in a single
program or subroutine. Different symbols are used to draw each
type of flowchart.
The Flowchart
A Flowchart
 shows logic of an algorithm
 emphasizes individual steps and their
interconnections
 e.g. control flow from one action to the next
ALGORITHMS …
Start/ Stop

Start Stop

Input/ Output

Read Write
Algorithms …
Process box
❑ Use not more than two statements in each box.
Sum:= Sum + 1;
Count:= Count + 1;
ALGORITHMS …
Decision/selection box
ALGORITHMS …
Direction line (next step)

❑ Natural left to right (no arrow indicator)

❑ Natural top to down (no arrow


indicator)

❑ Other directions are as


indicated:
ALGORITHMS …

Preparation box Connection circle


Rules For Creating Flowchart :

◼ A flowchart is a graphical representation of an algorithm.it


should follow some rules while creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with
an arrow line.
Rule 4: The decision symbol in the flowchart cannot be
associated with the arrow line.
Advantages of Flowchart:
• Flowcharts are a better way of communicating the logic of the
system.
• Flowcharts act as a guide for blueprint during program
designed.
• Flowcharts help in debugging process.
• With the help of flowcharts programs can be easily analyzed.
• It provides better documentation.
• Flowcharts serve as a good proper documentation.
• Easy to trace errors in the software.
• Easy to understand.
• The flowchart can be reused for inconvenience in the future.
• It helps to provide correct logic.
Disadvantages of Flowchart:
• It is difficult to draw flowcharts for large and complex
programs.
• There is no standard to determine the amount of
detail.
• Difficult to reproduce the flowcharts.
• It is very difficult to modify the Flowchart.
• Making a flowchart is costly.
• Some developer thinks that it is waste of time.
• It makes software processes low.
• If changes are done in software, then the flowchart
must be redrawn
PSEUDO CODE
• Most programs are developed using programming
languages.
• These languages have specific syntax that must be
used so that the program will run properly.
• Pseudo-code is not a programming language.
• Instead, it is a simple way of describing a set of
programming instructions in a manner that
resembles a programming language.
• Pseudo-code has its own syntax, some of which is
very similar to many actual programming languages.
• Any algorithms designed using pseudo-code will
not run unless they are converted into an actual
programming language.
example
◼ WHILE answer <> 'computer science'
DO SEND 'What is your favourite
subject?' TO DISPLAY RECEIVE
answer FROM (STRING)
KEYBOARD IF answer = 'computer
science' THEN SEND 'Good
choice!' TO
DISPLAY ELSE SEND
'Really? ' TO DISPLAY END IF
END WHILE
Advantages
• it can be quickly and easily converted into an
actual programming language as it is similar to
a programming language
• it is fairly easy to understand, even for non-
programmers
• it does not matter if there are errors in the
syntax - it is usually still obvious what is
intended
• changes to the design can be incorporated
quite easily
Disadvantages:

• It can be hard to see how a program


flows. For example, where does following
one path as opposed to another take the
program?
• It can be time consuming to produce.
Written descriptions
◼ Algorithms can also be ‘written descriptions’.
◼ There is no defined format for this, so
programmers are free to write as they wish.
Short sentences are best.
◼ An algorithm should be easy understand and
have no unnecessary detail.
◼ A recipe is a good example of clear instructions,
eg ‘stir’ and ‘bake’
◼ A written description should include all the
elements found when decomposing the problem.
Advantages and disadvantages of using
written descriptions

◼ Designing an algorithm using written


descriptions has advantages because:
• there is no need to worry about using
correct syntax
• it feels more natural to use normal writing

◼ The main disadvantage of a written


description is that there is a temptation to
use too many words.
 This makes the algorithm descriptive rather
than instructional.
Program code
◼ Program code can also be used to create an algorithm.
In this context it is called draft program code.
◼ There is no requirement for an algorithm to compile and
run so errors are acceptable so long as the meaning is
clear.
◼ Designing an algorithm using program code has the
following advantages:
• program code is very familiar
• the syntax doesn’t have to be completely correct
• all the possible elements required will be present in the language -
unlike pseudo-code
◼ Program code algorithms also have their disadvantages:
• it is possible for the whole design stage of creating an algorithm to be
missed
• decomposition might not have been completed
PROGRAMMING
CONSTRUCTS
◼ Programs are designed using common building
blocks. These building blocks, known as
programming constructs, form the basis for all
programs.
◼ There are three basic building blocks to
consider:
◼ sequence
◼ selection
◼ iteration
Sequence
◼ Sequence is the order in which instructions occur and are
processed. Selection determines which path a program takes when
it is running. Iteration is the repeated execution of a section of code
when a program is running.
◼ There are two types of iteration:
◼ Sequence is the first programming construct. In
programming, statements are executed one after another. Sequence is
the order in which the statements are executed.
◼ The sequence of a program is extremely important as carrying
out instructions in the wrong order leads to a program performing
incorrectly.

Example

Start:
process A;
process B;
Process
Stop:
Repetition/iteration/looping
• There are times when a program needs to repeat certain
steps until told otherwise, or until a condition has been
met.
• This process is known as iteration.
• Iteration is also often referred to as looping, since the
program ‘loops’ back to an earlier line of code. Sections of
codes that are iterated are called loops.
• Iteration enables programmers to greatly simplify
a program.
• Instead of writing out the same lines of code again and
again, a programmer can write a section of code once, and
ask the program to execute it again and again until no
longer needed.
Example

This program would print The program can be


a message out six times: written as
print(“Coding is cool”)
print(“Coding is cool”)
for count = 1 to
print(“Coding is cool”) 6 print(“Coding
print(“Coding is cool”)
print(“Coding is cool”)
is cool”) next
print(“Coding is cool”) count
REPETITION
These are steps that must be performed more than once.
DO WHILE

Start:
DO WHILE:
Process;
Do exit action;
ENDWHILE:
Algorithms …
REPETITION
These are steps that must be performed more than once.

Start:
REPEAT:
Process
Until condition adjustment
UNTIL condition holds
Selection
◼ Selection is the second programming construct.
◼ In programming, there are occasions when a decision
needs to be made. Selection is the process of making a
decision.
◼ The result of the decision decides which path
the program will take next.
◼ For example, a program could tell a user whether they
are old enough to learn how to drive a car.
◼ If the user's age meets the required driving age, the
program would follow one path and execute one set
of instructions.
◼ Otherwise, it would follow a different path and execute a
different set of instructions.
Example
◼ age = int(input("How old are
you? ")
◼ if age > 16 then print("You are
old enough to drive a car!")
else
◼ print("Come back when you are
older!") endif
Algorithms …
DECISION/ SELECTION

IF condition holds
THEN perform Process
IF condition THEN
…. ELSE …
Example
START
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Input
M1,M2,M3,M4
Step 3: if (GRADE <50) then
Print “FAIL”
else
GRADE(M1+M2+M3+M4)/4 Print “PASS”
endif
N IS Y
GRADE<5
0

PRINT PRINT
“PASS” “FAIL”

STOP
Example 2
◼ Write an algorithm and draw a flowchart to
convert the length in feet to centimeter.
Pseudocode:
◼ Input the length in feet (Lft)
◼ Calculate the length in cm (Lcm) by
multiplying LFT with 30
◼ Print length in cm (LCM)
Example 2
Flowchart
Algorithm START

◼ Step 1: Input Lft


Input

◼ Step 2: Lcm  Lft x 30


Lft

◼ Step 3: Print Lcm Lcm  Lft x 30

Print
Lcm

STOP
Example 3
Write an algorithm and draw a flowchart that
will read the two sides of a rectangle and
calculate its area.
Pseudocode
◼ Input the width (W) and Length (L) of a rectangle
◼ Calculate the area (A) by multiplying L with W
◼ Print A
Example 3
Algorithm START

◼ Step 1: Input W,L Input


W, L
◼ Step 2: A  L x W
◼ Step 3: Print A ALxW

Print
A

STOP
Flowchart – example 1
Begin

Read birth date

Calculate
Age = current year – birth date

Display
age

End

Principles of Programming - NI July


2005 53
Flowchart – example 2
Begin

Read age

YES Age > 55? NO

print “Pencen” print “Kerja lagi”

End

Principles of Programming - NI July


2005 54
Flowchart – example 5
Begin

sum = 0
current_number = 1

NO
current_number <= 10? print sum

YES
End
sum = sum + current_number
current_number = current_number + 1

Principles of Programming - NI July


2005 55
Example 4
◼ Write an algorithm and draw a flowchart that
will calculate the roots of a quadratic equation
ax2 + bx + c = 0
◼ Hint: d = sqrt ( b2 − 4ac ), and the roots are:
x1 = (–b + d)/2a and x2 = (–b – d)/2a
Exercises: Algorithm &
Flowchart
1.) Create an algorithm and a flowchart that
will accept/read two numbers and then
display the bigger number.
Exercises: Algorithm &
Flowchart
2.) Create an algorithm and a flowchart that
will compute the area of a circle.
Exercises: Algorithm &
Flowchart
3.) Create an algorithm and a flowchart that
will compute the sum of two numbers. If
the sum is below or equal to twenty, two
numbers will be entered again. If the sum
is above 20, it will display the sum.
Lab Activity: Algorithm &
Flowchart
4) Create an algorithm and a flowchart that
will output the largest number among the
three numbers.
Assignment 1

1. Create an algorithm and a flowchart that will output for g.c.d.


2. Create an algorithm and a flowchart that will output the factorial of a
given number.
3. Create an algorithm and a flowchart that will output the Fibonacci
series up to a given number.
4. Create an algorithm and a flowchart that will output all the prime
numbers between 2 numbers.

You might also like