0% found this document useful (0 votes)
11 views45 pages

Lecture 4 - Introduction To Algorithms

Algorithm

Uploaded by

mathewmuthoni5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views45 pages

Lecture 4 - Introduction To Algorithms

Algorithm

Uploaded by

mathewmuthoni5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

Introduction to

Algorithms

1
Introduction to Algorithms
 Problems, Algorithms and Programs
 Programmers deal with:
 Problems,
 Algorithms and
 Computer programs.

2
Problems

 Problem: a task to be performed.


 Best thought of as inputs and expected outputs.
 Problem definition should include constraints on
the resources such as memory and storage space
that may be consumed by any acceptable
solution.

3
Algorithms and Programs
• An algorithm gives us a “recipe” for solving the problem by
performing a series of steps, where each step is completely
understood and achievable.

• An algorithm takes the input to a problem and transforms it to


the output. A mapping of input to output.

• A problem can be solved by many algorithms.

4
Programs
 A computer program is a concrete representation of an
algorithm in some programming language.
 Naturally, there are many programs that are instances of the
same algorithms, since any modern programming language

can be used to implement any algorithm.

5
ALGORITHMS …
 An algorithm is the series of steps that are used to
solve a programming problem.
 It may also be considered as a plan for solving a
programming problem that specifies the sequence
of steps used in the solution.
 The following are mandatory features that an
algorithm must have:
(I) An algorithm must have a start and an end
point.
(II)Every step must be performable:-
(A) using a finite amount of resources
(B) in a finite amount of time.
6
Qualities of a good algorithm.

• An algorithm possesses the following properties:


 It must be correct.

 It must be composed of a series of concrete steps.

 There can be no ambiguity as to which step will be

performed next.
 It must be composed of a finite number of steps.

 It must terminate.

7
ALGORITHMS DESIGN TOOLS

 The most common means of representing


algorithms is by the use of
flowcharts
pseudo code.
 We will examine each of these.

8
ALGORITHMS …

Flow Charts
 A flowchart is a diagram that depicts the “flow” of a
program. They are typically used to show a
program’s logic.
 Flowcharts are a modeling technique that were
introduced in the 1940/50s and popularized for
structured development in the 1970s
 Can be implemented using any programming
language we want i.e. flow charts are language
independent
 Flow charts are also easy for non-programmers to
understand.
9
ALGORITHMS …

• Flowcharts are constructed using a set of


standard symbols some of which are:
– Rounded rectangles – Show the terminals ie start and
stop of the program logic
– Parallelograms – Represents data entry or output
– Rectangle - indicates a process such as a mathematical
computation or variable assignment
– Rhombus/ diamond – Represents a decision
– Circle – Off page connector to show the continuation of
the flowchart.
– Arrow – Shows the flow

10
ALGORITHMS DESIGN TOOLS
Flow Chart
 Each symbol contains information on what must be
done at that particular point
 The arrow shows the order in which the
instructions must be executed
Input/ Output Start/Stop

Read Write Start Stop

11
Stepping Through the Flowchart

Your gross
pay is 800 START

Read Hours, Pay Rate

Gross Pay= Hours x Pay Rate

Variable Contents: Display Gross


Pay
Hours: 40
Pay Rate: 20 END
Gross Pay: 800
ALGORITHMS …

Flow Chart Symbols …

Process box
 Use not more than two statements in each box.

Sum:= Sum + 1;
Count:= Count + 1;

13
ALGORITHMS …

Flow Chart Symbols …


Decision/selection box
 Based on the value of the decision parameter,
follow one of the two available paths

14
Connectors

• The “A” connector indicates that the second


flowchart segment begins where the first
segment ends.

START A

END
A
ALGORITHMS …

Pseudocode
Pseudocode is a narrative representation of an
algorithm using English like statements.
Flowcharts were the first design tool to be widely
used, but unfortunately they do not reflect some of
the concepts of structured programming very well.
Pseudocode is a newer tool and has features that
make it more reflective of the structured concepts.
The drawback is that the narrative presentation is
not as easy to understand or follow.
ALGORITHMS …

Rules for Pseudocode..

• Write only one statement per line


 Capitalize initial keyword

 Indent to show hierarchy

 End multiline structures

 Keep statements language independent


One Statement Per Line
Each statement in pseudocode should express just
one action for the computer. If the task list is properly
drawn, then in most cases each task will correspond
to one line of pseudocode.

Task List
Pseudocode
• Read name, hours worked, rate of
pay READ name, hoursWorked,
payRate
• Perform calculations
gross = hoursWorked * payRate
• gross = hours worked * rate of
pay WRITE name, hoursWorked,
gross
• Write name, hours worked, gross
Capitalize Initial Keyword

In the example above note the words: READ and WRITE.


These are just a few of the keywords to use, others
include:READ, WRITE, IF, ELSE, ENDIF, WHILE, ENDWHILE

Pseudocode
READ name, hoursWorked, payRate
gross = hoursWorked * payRate
WRITE name, hoursWorked, gross
Indent to Show Hierarchy

Each design structure uses a particular indentation


pattern
• Sequence:
Keep statements in sequence all starting in the same column
• Selection:
Indent statements that fall inside selection structure, but not the keywords that form the
selection
• Loop:
Indent statements that fall inside the loop but not keywords that form the loop
READ name, grossPay, taxes
IF taxes > 0
net = grossPay – taxes
ELSE
net = grossPay
ENDIF
WRITE name, net
End Multiline Structures

READ name, grossPay, taxes


IF taxes > 0
net = grossPay – taxes
ELSE
net = grossPay
ENDIF
WRITE name, net

See the IF/ELSE/ENDIF as constructed above, the ENDIF is


in line with the IF.

The same applies for WHILE/ENDWHILE etc…


Language Independence

Resist the urge to write in whatever language you are


most comfortable with, in the long run you will save time.
Remember you are describing a logic plan to develop a
program, you are not programming!
Advantages & Disadvantages

Flowchart Advantages: Pseudocode Advantages


 Standardized  Easily modified
 Visual  Implements structured
concepts
 Done easily on Word Processor

Flowchart Pseudocode
Disadvantages: Disadvantages:
 Hard to modify  Not visual
 Structured design  No accepted standard,
elements not varies from company to
implemented company
 Special software required
Program control structures
 Programming constructs are the building
blocks of a structured program. There are
only three programming control structures.
 These are:
 Sequence
 Selection (Decision/branching)
 Iteration (Looping/Repetition)
Sequence Structure

• In sequence control, the computer executes


instructions that follow one after the other. The
program samples considered earlier are purely
sequential
Decision Structure
• A decision based on a Boolean test has to be made
before a computer executes either of the
statements. The Boolean test returns either true or
false.
• For example, if the Boolean test seeks to test if
X > 50 and the user enters 60, the value returned is
true.
• Decision control is also referred to as branching
Decision Structure
• In the flowchart segment below diamond, indicates a yes/no
question. If the answer to the question is yes, the flow follows
one path. If the answer is no, the flow follows another path

NO YES
Decision Structure

• In the flowchart segment below, the question “is x < y?” is


asked. If the answer is no, then process A is performed. If the
answer is yes, then process B is performed.

NO YES
x < y?

Process A Process B
Decision Structure
• The flowchart segment below shows how a decision structure
is expressed in C++ as an if/else statement.

Flowchar C/C++ Code


NO t YES
x < y?
if (x < y)
a = x * 2;

Calculate a Calculate a else


as x plus as x times
y. 2. a = x + y;
Decision Structure
• The flowchart segment below shows a decision structure with
only one action to perform. It is expressed as an if statement
in C++ code.

C/C++ Code

NO YES if (x < y)
x < y? a = x * 2;

Calculate a
as x * 2.
Repetition Structure
• A repetition structure represents part of the program that
repeats. This type of structure is commonly known as a loop.
Repetition Structure
• A loop tests a condition, and if the condition exists, it
performs an action. Notice the use of the diamond symbol
Then it tests the condition again. If the condition still exists,
the action is repeated. This continues until the condition no
longer exists.
Repetition Structure
• In the flowchart segment, the question “is x < y?” is asked. If
the answer is yes, then Process A is performed. The question
“is x < y?” is asked again. Process A is repeated as long as x is
less than y. When x is no longer less than y, the repetition
stops and the structure is exited.

YES
x < y? Process
A
Repetition Structure
• The flowchart segment below shows a repetition structure
expressed in C++ as a while loop.

C/C++ Code

while (x < y)

YES {
x < y? Add 1 to x x++;
}
Controlling a Repetition Structure

• The action performed by a repetition structure must


eventually cause the loop to terminate. Otherwise, an infinite
loop is created.
• In this flowchart segment, x is never changed. Once the loop
starts, it will never end.
• QUESTION: How can this
flowchart be modified so
YES
it is no longer an infinite x < y? Display x
loop?
A Pre-Test Repetition Structure

• This type of structure is known as a pre-test repetition


structure. The condition is tested BEFORE any actions are
performed.

YES
x < y? Display x Add 1 to x
A Pre-Test Repetition Structure

• In a pre-test repetition structure, if the condition does not


exist, the loop will never begin.

YES
x < y? Display x Add 1 to x
A Post-Test Repetition Structure

• This flowchart segment shows a post-test


repetition structure.
• The condition is tested AFTER the actions
are performed. Display x

• A post-test repetition structure always


performs its actions at least once. Add 1 to x

YES
x < y?
A Post-Test Repetition Structure

• The flowchart segment below shows a post-test repetition


structure expressed in C++ as a do-while loop.)

C Code
Display
x do
{
Add 1 to x
printf(“X is %x,x)
x++;
} while (x < y);

YES
x < y?
Combining Structures
• Structures are commonly combined to create more complex
algorithms.
• The flowchart segment below combines a decision structure
with a sequence structure.

YES
x < y? Display x Add 1 to x
Combining Structures
• This flowchart segment shows two decision structures
combined.

NO YES
x>
min?

Display “x is NO YES
outside limits.”
x<
max?

Display “x is “x is within
outside limits.” limits.”
SAMPLE ALGORITHMS …

 An Algorithm To Compute The Sum Of N Numbers


Pseudocode
START
Variables: Sum, Count, Number, Number_of_items
Sum:=0;
Count:=0;
READ Number_of_items;
REPEAT
READ Number;
Count:=Count+1;
Sum:=Sum+Number;
UNTIL Count=Number_of_items;
DISPLAY Sum;
STOP
42
SAMPLE ALGORITHMS …
 Algorithm For Computing The Factorial Of A Number
Less Than 12
1. Start
2. Setup variables: Count, Number, Factorial
3. Initialize variables:
Count=0;Number=0;Factorial=1;
4. Read a Number
5. Check exceptions: Number<0(advice and ask again);
Number>12(advice and ask again), Number=0 or 1
(Factorial=1);
6. If Number<2 then proceed to 10
Add 1 to Count
Factorial = Factorial x Count
7. If Count<Number Repeat from 7
Display Factorial
8. Stop
43
SAMPLE ALGORITHMS …
 Algorithm For Computing The Factorial Of A
Number Less Than 12
flowchart

44
SAMPLE ALGORITHMS …
 Algorithm For Computing The
… Factorial Of A Number Less
Than 12
Pseudocode
START
Variables: Count, Number, Factorial
Count:=0;
Number:=-10;
Factorial:=1;
DO WHILE (Number <0 or Number>12)
PROMPT ‘Enter a number between 0 and 12’
READ Number
If Number <0 or Number>12
WRITE ‘Number should be 0..12’
ENDWHILE
45

You might also like