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

INTRODUCTION TO COMPUTER PROGRAMMING & ALGORITHM

Chapter 2 Program Algorithm


2.1 Introduction
 An algorithm is any well-defined computational procedure that takes some value, or set of values, as
input and produces some value, or set of values, as output. An algorithm is thus a sequence of
computational steps that transform the input into the output.
 An Algorithm is a logical sequence of discrete steps that describe a complete solution to a given problem
in a finite amount of time independently of the software or hardware of the computer. It is the set of
rules that define how a particular problem can be solved in finite number of steps

An algorithm can be viewed as a tool for solving a well-specified computational problem. The statement of
the problem specifies in general terms the desired input/output relationship. The algorithm describes a
specific computational procedure for achieving that input/output relationship. Algorithms are very essential
as they instructs the computer what specific steps it needs to perform to carry out a particular task or solve a
problem.

2.2. Characteristics of an Algorithm


Every algorithm should have the following five characteristics:
1) Input; takes in some value(s) as input
2) Output; produces some value(s) as output
3) Definiteness / non ambiguity: It must be precise and unambiguous. the statements must be interpretable
in a unique way by whom is executing them
4) Executability / Effectiveness: It must be possible to execute each statement and it must give the
correct solution in all cases
5) Termination (finiteness): It must eventually end. The execution of the algorithm must terminate in a
finite amount of time for each possible set of input data

2.3. Efficiency and Analysis of the Algorithm


1) Efficiency: The efficiency of an Algorithm means how fast it can produce the correct results for the
given problem. The Algorithm efficiency depends upon its time complexity and space complexity. The
complexity of an algorithm is a function that provides the running time and space for data, depending on
the size provided by us. Two important factors for judging the complexity of an Algorithm are;
a) Space complexity which refers to the amount of memory required by the algorithm for it execution
and generation of the final output.
b) Time Complexity which refers to the amount of computer time required by an algorithm for its
execution, which includes both the compile time and run time.
The compile time of an algorithm does not depend on the instance characteristics of the algorithm. The
run time of an algorithm is estimated by determining the number of various operation, such as addition,
subtraction, multiplication, division, load and store executed by it.

2) Algorithm Analysis: The analysis of an algorithm determines the amount of resources, such as time and
space required by it for its execution. Generally, the algorithms are formulated to work with the inputs or
arbitrary length. Algorithm analysis provides theoretical estimates required by an algorithm to solve a
problem.

2.4. Designing Algorithms


Algorithm design is a specific method to create a mathematical process in problem solving processes. There
are many ways to design algorithms.
1) Divide and conquer.

Intro to Programming. Chapter 2 Program Algorithm Page 1


a) Divide the problem into a number of sub-problems.
b) Conquer the sub-problems by solving them recursively. If the sub-problem sizes are small
enough, however, just solve the sub-problems in a straightforward manner.
c) Combine the solutions to the sub-problems into the solution for the original problem.

2) Dynamic programming: is a method for solving a complex problem by breaking it down into a
collection of simpler sub-problems, solving each of those sub-problems just once, and storing their
solutions. Dynamic programming algorithms are often used for optimization. A dynamic programming
algorithm will examine the previously solved sub-problems and will combine their solutions to give the
best solution for the given problem.

3) Greedy algorithm: is an algorithmic paradigm that follows the problem solving heuristic of making the
locally optimal choice at each stage with the hope of finding a global optimum.
In general, greedy algorithms have five components:
a) A candidate set, from which a solution is created
b) A selection function, which chooses the best candidate to be added to the solution
c) A feasibility function, that is used to determine if a candidate can be used to contribute to a solution
d) An objective function, which assigns a value to a solution, or a partial solution, and
e) A solution function, which will indicate when we have discovered a complete solution
Greedy algorithms produce good solutions on some mathematical problems, but not on others.

4) Back Tracking. is a general algorithm for finding all (or some) solutions to some computation al
problems, notably constraints satisfaction problems, that incrementally builds candidates to the
solutions, and abandons each partial candidate ("backtracks") as soon as it determines that the candidate
cannot possibly be completed to a valid solution.

Backtracking is an important tool for solving constraint satisfaction problems, such as crossword, verbal
arithmetic, Sudoku and many other puzzles.

5) Brute Force: A general problem-solving technique that consists of systematically enumerating all
possible candidates for the solution and checking whether each candidate satisfies the problem's
statement.

2.5. Steps in development of Algorithms


1) Problem definition
2) Development of a model
3) Specification of Algorithm
4) Designing an Algorithm
5) Checking the correctness of Algorithm
6) Analysis of Algorithm
7) Implementation of Algorithm
8) Program testing
9) Documentation Preparation

2.6. Program Control Structures


Programming procedures no matter how complex may be reduced to a combination of control structures.
Control structures specify the statements to be executed and the order of execution of statements. There are
three kinds of control structures:
1) Sequential—instructions are executed in linear order
2) Selection (branch or conditional) - The logic of the program may require execution of a statement based
on a decision. A true/false question determines the selection of the next instruction based on the answer
3) Iterative (loop) – a block of instructions may need to be repetitively executed until a certain condition is
met.

Intro to Programming. Chapter 2 Program Algorithm Page 2


2.7. Algorithm Representation
The steps of an Algorithm, they can be presented using Flow charts and pseudo-codes.

2.7.1 Flow Charts


A flowchart is a diagrammatic representation of the logic for solving a task. A flow chart is a traditional
means of showing in diagrammatic form, the sequence of steps to be undertaken in solving a problem.
Flowcharts or flow diagrams are important tools in writing a computer program. A flowchart allows you to
plan the sequence of steps in a program before writing it. The flowchart serves as a visual representation
which many programmers find indispensable in planning any program of at least moderate complexity.

A flowchart is drawn using boxes of different shapes with lines connecting them to show the flow of control.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.

2.7.1.1. Symbols / Elements of a Flowchart.


A flowchart consists of a set of boxes, the shapes of which indicate specific operations. The separate boxes
are connected with arrows to show the sequences in which the various operations are performed. The most
common symbols that are used to draw a flowchart are—Process, Decision, Data, Terminator, Connector
and Flow lines

A flowchart may be simple or complex. While drawing a flowchart, some rules need to be followed
1) A flowchart should have a start and end,
2) The direction of flow in a flowchart must be from top to bottom and left to right, and
3) The relevant symbols must be used while drawing a flowchart.

Shape Name Description


Rectangle Process symbol: Used to represent any kind of processing
activity. Details are written in the box

Calculate wages

Diamond: The decision Symbol: Used where a decision has to be


made in selecting the subsequent path to be followed.

Is the
transaction a
credit?

Used to show the flow/ path of ma sequence of symbols.


 Vertical line without arrow head are assumes t flow top
to bottom.
 Horizontal lines without arrow heads are assumed to
flow left to right.
 Every operation box must have at least one incoming or
outgoing arrow. Any arrow leaving a decision box must
be labeled with the decision result which will cause that
path to be followed.

Intro to Programming. Chapter 2 Program Algorithm Page 3


Input/output symbol: Used where data input is to be
Parallelogram performed

The Terminal symbol: Used as the first or last symbol in a


Oval program or separately drawn program module

Start
Stop

Connector symbol:
Small Circle
Exit to or entry from another part of the chart
Or

Used to add explanatory notes or description,

2.7.1.2. Representing the Program Control Structures


While preparing the flowchart, the sequence, selection or iterative structures may be used wherever required.
The Flow charts for the control structures are as follows;

 Sequence: In a sequence, the steps are executed in linear order one after the other.
 Selection / Branching: the step to be executed next is based on a decision taken. If the
condition is true (yes) a different path is followed than if the condition evaluates to false (no).
 Interation / looping. In case of iterative operation, a condition is checked. Based upon the
result of this conditional check, true or false, different paths are followed. Either the next step in
the sequence is executed or the control goes back to one of the already executed steps to make a
loop.

Intro to Programming. Chapter 2 Program Algorithm Page 4


Examples

1) The first flowchart computes the product of any two numbers and gives the result. The flowchart is a
simple sequence of steps to be performed in a sequential order.
2) The second flowchart compares three numbers and finds the maximum of the three numbers. This
flowchart uses selection. In this flowchart, decision is taken based upon a condition, which decides the
next path to be followed, i.e. If A is greater than B then the true (Yes) path is followed else the false
(No) path is followed. Another decision is again made while comparing MAX with C.
3) The third flowchart finds the sum of first 100 integers. Here, iteration (loop) is performed so that some
steps are executed repetitively until they fulfill some condition to exit from the repetition. In the decision
box, the value of I is compared with 100. If it is false (No), a loop is created which breaks when the
condition becomes true (Yes).

2.7.1.3. Limitations of program flowcharts


1) Not easily translated into programming language.
2) A complex and long flowchart may run into multiple pages, which becomes difficult to understand and
follow.
3) Updating a flowchart with the changing requirements is a challenging job.

2.7.2. Pseudo code


Pseudo code consists of short, readable and formally-styled English language used for explaining an
algorithm.

Intro to Programming. Chapter 2 Program Algorithm Page 5


Pseudo code is halfway between English and programming language and is based upon a few
simple grammatical construction which avoid the ambiguities of English but which can be easily
converted into computer programming language.

Pseudo code is a short-hand way of describing a computer program. It is an informal high-level description
of a computer programming algorithm, which omits details that are not essential for human understanding of
the algorithm. Using pseudo code, it is easier for a programmer or a non-programmer to understand the
general working of the program, since it is not based on any programming language. It is used to give a
sketch of the structure of the program, before the actual coding. It uses the structured constructs of the
programming language but is not machine-readable.

2.7.2.1 Representing the Control Structures

Examples
1. Finding the Product of two numbers

Intro to Programming. Chapter 2 Program Algorithm Page 6


2. Finding Maximum of any Three numbers

3. Finding of first 100 numbers

2.7.2.2. Limitations of Pseudo Code


1) Pseudo code cannot be compiled or executed.
2) No standard for the syntax of pseudo code exists.

For writing the pseudo code, the programmer is not required to know the programming language in which
the pseudo code will be implemented later.

2.8. Representing Program Control Structures using Flow Chart & Pseudo code
Control Structure Pseudo code Flow Chart
Sequence: 1st Instruction
In the absence of selection, or
repetition, program statements 2nd Instruction
are executed in the sequence in
which the appear in the program 3rd Instruction

Selection IF
Part of decision making and condition Yes
No
allows alternative actions to be THEN
?
taken according to the conditions actions
that exist at particular stages in ELSE
program execution actions
ENDIF
Or

Intro to Programming. Chapter 2 Program Algorithm Page 7


CASE
a). Actions
?
b). Actions
c). Actions
d). Actions
ENDCASE a b c

Repetition also called “looping”


There are many programming WHILE
problems in which the same condition
sequence of statements needs to DO
?
be performed again and again for Actions
No
a definite or indefinite number ENDWHILE
of times

REPEAT
actions
UNTIL
condition
No
?
Yes

Exercises
Develop the Algorithm and represent using both Flow Chart and Pseudo code that would solve the following
problem

1. A Construction company which hires casual works intends to computerize their wages calculation
process. The company wages payment policy is as follows;
a) The company has a 5 days working week.
b) Men are paid Ksh 250 per day while women are paid Ksh 200 per day
c) Extra day is paid at Ksh 50 more than the Normal working day.

2. Develop a program to calculate the area and perimeter of a Square.

3. A Bank intends to automate the calculation of bonuses for account holders at the end of every year. The
Bank’s policy is to give a 2% bonus on the ending balance of all accounts at the end of the year. A 5%
bonus is also given to all Female account holders if the balance is more than 50,000.

Intro to Programming. Chapter 2 Program Algorithm Page 8

You might also like