0% found this document useful (0 votes)
1 views

Algorithms

This document provides an overview of algorithms and flowcharts in computer programming, emphasizing their roles in problem-solving and program development. It outlines learning objectives, definitions, properties of algorithms, and various representation methods such as flowcharts and pseudocode. Additionally, it discusses the advantages and limitations of these tools, as well as key programming constructs like sequence, selection, and repetition.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Algorithms

This document provides an overview of algorithms and flowcharts in computer programming, emphasizing their roles in problem-solving and program development. It outlines learning objectives, definitions, properties of algorithms, and various representation methods such as flowcharts and pseudocode. Additionally, it discusses the advantages and limitations of these tools, as well as key programming constructs like sequence, selection, and repetition.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

TOPIC: ALGORITHM AND FLOWCHART

Class: Comp. Sc. A/L

The computers work on a set of instructions called computer program, which clearly
specifies the way to carry out a task. An analogy of this may be thought of as the instructions
given by the manager or team leader to its team. The team members follow those instructions
and accordingly perform their duties. Similarly, a computer also takes instructions in the form
of computer programs to carry out the requested task. This chapter aims to

Learning objectives
After studying this lesson, student should be able to:
 Discuss what an algorithm is and how to use it to represent the solution of a
problem.
 Use Flowchart and Pseudocode represent algorithms
 Discuss the importance of testing, debugging and documentation on the process of
program development.
 Discuss some concepts Object-Oriented Programming

Contents

I. DEVELOPING A PROGRAM......................................................................................................2
II. ALGORITHM...............................................................................................................................4
III. REPRESENTATION OF AN ALGORITHM...........................................................................5
IV. ALGORITHM STRUCTURES...............................................................................................10
V. PROGRAM TESTING AND DEBUGGING..............................................................................17
VI. PROGRAM DOCUMENTATION..........................................................................................18
VII. PROGRAMMING PARADIGMS...........................................................................................21
VIII. OBJECT ORIENTED PROGRAMMING (OOP)...................................................................22
Topic: Introduction to programming2

I. ALGORITHM

II.1. Definition
Algorithms are one of the most basic tools that are used to develop the problem-solving logic.
An algorithm is defined as a finite sequence of explicit instructions that when provided with
a set of input values, produces an output and then terminates.To be an algorithm, the steps
must be unambiguous and after a finite number of steps, the solution of the problem is
achieved.

Different algorithms may accomplish the same task, with a different set of instructions, in
more or less the same time, space, and efforts. For example, two different recipes for
preparing tea, one 'add sugar' while 'boiling water' and the other 'after boiling water' produce
the same result.

II.2. Properties of an algorithm


Note that algorithms are not computer programs, as they cannot be executed by a computer.
Some properties of algorithm are as follows:

• Non ambiguous: There must be no ambiguity in any instruction.


• Coherent: There should not be any uncertainty about which instruction is to be
executed next.
• The description of the algorithm must be finite. An algorithm cannot be open-ended.
• Finiteness: It should terminate after a finite number of steps.
• It must be general enough to deal with any contingency.

II.3. Example of algorithm


We use algorithms in our daily life. For example, to determine the largest number out of three
numbers, A, B, and C, the following algorithm may be used.

Algorithm: To determine largest of three numbers


1. Start
2. Read three numbers A, B, C
3. Find the larger number between A and B and store it in MAX_AB
4. Find the larger number between MAX_AB and C and store it in MAX
5. Display MAX
6. Stop
The above-mentioned algorithm terminates after six steps. This explains the feature of
finiteness. Every action of the algorithm is precisely defined; hence, there is no scope for
ambiguity.
Topic: Introduction to programming3

II. REPRESENTATION OF AN ALGORITHM

Algorithms can be represented in different ways:

- By Flowchart
- By Pseudocode

III.1. Flowchart
A flowchart helps to clarify how things are currently working and how they could be
improved. It also assists in finding the key elements of a process by drawing clear lines
between where one process ends and the next one starts.Flowcharts help in revealing
redundant or misplaced steps. In addition, they help in establishing important areas for
monitoring or data collection and to identify areas for improvement or increase in efficiency.

a) Flowchart Symbols

A flowchart is drawn according to defined rules and using standard flowchart symbols
prescribed by American National Standard institute (ANSI). Some standard symbols that are
frequently required for flowcharts are shown:

Symbol Symbol name Description


Flow lines are used to connect symbols. These lines
Flow Lines indicate the sequence of steps and the direction of
flow.
The symbol is used to represent the beginning (start),
Terminal the termination (end) or halt (pause) in the program
logic.
Process symbol is used for representing arithmetic and
data movement instructions. It can represent a single
Processing
step (‘add two cups of flour), or an entire sub- process
(‘make bread’) within a larger process.
Process symbol is used for representing arithmetic and
data movement instructions. It can represent a single
Decision
step (‘add two cups of flour), or an entire sub- process
(‘make bread’) within a larger process.
This symbol represents information entering or leaving
Input/output the system such as customer order (input) and
servicing (output)
It is used to provide additional information about
another flowchart symbol. The content may be in the
Annotation
form of descriptive comments, remarks or explanatory
notes.
Connector Connector symbol is used to join different flow lines.
Topic: Introduction to programming4

Off- page This symbol is used to indicate the flowchart continues


Connecter on the next page
Document is used to represent a paper document
Document
produced during the flowchart process.
Manual input symbol represents input to be given by a
Manual Input
developer / programmer.
Manual Manual operation symbol shows that the process has to
Operation be done by a developer/ programmer.
This is used to represent data input or output from and
Magnetic Disk
to a magnetic disk.
Predefined This symbol represents the operation or process that
process has been previously specified elsewhere.
Multipage This symbol is used to represent a document with
document multiple pages.
This symbol is used to represent data input or output
Magnetic tape
from and to a magnetic tape.

b) Guidelines for Preparing Flowcharts

The following guidelines should be used for creating a flowchart:

• The flowchart should be clear, neat and easy to follow.


• It must have a logical start and finish.
• In drawing a proper flowchart, all necessary requirements should be listed in logical
order.
• Only one flow line should come out from a process symbol.

• Only one flow line should enter a decision symbol. However, two or three flow lines
(one for each possible answer) may leave the decision symbol.

• Only one flow line is used with a terminal symbol.


Topic: Introduction to programming5

• Within standard symbols, write briefly. If necessary, use the annotation symbol to
describe data or process more clearly.
• In case of complex flowcharts, connector symbols are used to reduce the number of
flow lines.


• Intersection of flow lines should be avoided to make it a more effective and better
way of representing communication.
• It is useful to test the validity of the flowchart by passing through it with
normal/unusual test data.

c) Advantages of flowchart

The flowchart shows how the program works before you begin actually coding it. Some
advantages of flowcharting are the following.

- Communication: Flowcharts are helpful in explaining the program to other people.


- Effective analysis: With the help of flowchart, the problem can be analysed more
effectively
- Proper documentation: Program flowchart serves as a good program documentation,
which is needed for various purposes.
- Efficient coding: Once the flowchart is drawn, it becomes easy to write the program
in any high level language
- Proper debugging: The flowchart help in the debugging process
- Efficient program maintenance: The maintenance of operating program become
easy with the help of flowchart

d) Limitations of Flowcharts

Flowchart can be used for designing the basic concept of the program in pictorial form, but
cannot be used for programming purposes. Some of the limitations of the flowchart are given
below:

• Complex: The major disadvantage in using flowcharts is that when a program is very
large, the flowcharts may continue for many pages, making them hard to follow.
• Costly: If the flowchart is to be drawn for a huge program, the time and cost factor of
program development may get out of proportion, making it a costly affair.
Topic: Introduction to programming6

• Difficult to Modify: Due to its symbolic nature, any change or modification to a


flowchart usually requires redrawing the entire logic again, and redrawing a complex
flowchart is not a simple task.
• No Update: Usually, programs are updated regularly. However, the corresponding
update of flowcharts may not take place, especially in the case of large programs.

III.2. Pseudocode
Pseudocode (pronounced Soo-Doh-Kohd) is made up of two words: Pseudo and code.
'pseudo' means imitation and 'Code' refers to instructions, written in a programming language.
As the name suggests, pseudocode is not a real programming code, but it models and may
even look like a programming code. It is a generic way of describing an algorithm without
using any specific programming language notations. It uses plain English statements rather
than symbols, to represent the processes in a computer program. It is also known as program
design language (PDL)

a) Pseudocode Structures

Pseudocode allows the designer to focus on the logic of the algorithm without being
distracted by details of language syntax.The 'structured' part of pseudocode is a notation for
representing three general programming constructs: sequence, selection and repetition.Each
of these constructs can be embedded inside any other construct.These constructs represent the
logic or flow of control in an algorithm. It has been proven that three basic constructs for
flow of control are sufficient to implement any 'proper' algorithm.

Before going ahead with pseudocode, let us discuss some keywords, which are often used to
indicate input, output and processing operations.

• Input: READ, OBTAIN, GET and PROMPT


• Output: PRINT, DISPLAY and SHOW
• Compute: COMPUTE, CALCULATE and DETERMINE
• Initialize: SET and INITIALIZE
• Add One: INCREMENT

b) Example of pseudocode

The pseudocode given below calculates the area of a rectangle.

Pseudocode: To calculate the area of a rectangle

PROMPT the user to enter the length of the rectangle


PROMPT the user to enter the width of the rectangle
COMPUTE the area by multiplying the length with width
DISPLAY the area
STOP
Topic: Introduction to programming7

Note that the actions are flowing in a logical manner, that is, from top to bottom. There is no
branching and no process is repeated again. Each process is contributing something to the
next process.

c) Pseudocode Guidelines

Writing pseudocode is not a difficult task. Even if you do not know anything about the
computers or computer languages, you can still develop effective and efficient pseudocodes,
if you are writing in an organized manner. The main purpose of pseudocode is to help the
programmer to write efficient program code.By nature, pseudocode exists in various forms,
though most borrow syntax from popular programming languages (like C and FORTRAN).
Although there are no established standards for pseudocode construction, here are a few
general guidelines for developing pseudocodes:

- Statements should be written in simple English (or any preferable natural language)
and should be programming language independent.
- Steps must be clear, that is, unambiguous and when the steps (instructions) are
followed, they must suggest a solution to the specified problem.
- Be concise; you need not worry about programming language syntax, but can still be
precise.
- Each instruction should be written in a separate line and each statement in pseudocode
should express just one action for the computer.
- Capitalize keywords such as READ and PRINT.
- Each set of instructions is written from top to bottom, with only one entry and one
exit.

d) Advantages of Using Pseudocode

Some of the most significant benefits of pseudocode are as follows:

• Since it is language independent, it can be used by most programmers. It allows the


developer to express the problem logic in plain natural language.
• It is easier to develop a program from a pseudocode rather than from a flowchart or
decision table.
• Often, it is easy to translate pseudocode into a programming language, a step which
can be accomplished by less-experienced programmers.
• Unlike flowcharts, pseudocode is compact and does not tend to run over many pages.
Its simple structure and readability makes it easier to modify as well.
• Pseudocode allows programmers who work in different computer languages to talk to
each other.

e) Disadvantages of Using Pseudocode

Although pseudocode is a very simple mechanism to simplify problem-solving logic, it has


its own limitations. Some of the most notable limitations are as follows:
Topic: Introduction to programming8

• It does not provide visual representation of the program logic.


• There are no accepted standards for writing pseudocodes. Different programmers use
their own style of writing pseudocode.
• It is quite difficult for the beginners to write pseudocode as compared to drawing a
flowchart.

III. ALGORITHM STRUCTURES

Pseudocode and flowchart allow the designer to focus on the logic of the algorithm without
being distracted by details of language syntax. They describe the entire logic of the algorithm
so that the implementation becomes a mere mechanical task of translating line by line into a
source code.

The 'structured' part of pseudocode and flowchart is a notation for representing three general
programming constructs: sequence, selection and repetition. Each of these constructs can
be embedded inside any other construct. It has been proven that three basic constructs for
flow of control are sufficient to implement any 'proper' algorithm.

• Sequence, where information can flow in a straight line.


• Selection (branched), where the decisions are made according to some predefined
condition.
• Repetition, where the logic can repeat in a loop, that is, where a sequence of steps is
repeated until the desired output is obtained.

IV.1 Sequence
Sequence construct is a linear progression where one task is performed sequentially after
another. Sequential control is indicated by writing one action after another, each action on a
line by itself, and all actions aligned with the logical indent. The actions are performed in the
same sequence (top to bottom) in which they are written

Fig. Flowchart and Pseudocode for Sequence Construct


Topic: Introduction to programming9

Example

Flowchart Pseudocode C
START #include<stdio.h>
PROMPT for X main()
PROMPTfor Y {
SET X+Y to Z int X,Y,Z;
DISPLAY Z printf(“Enter the first value”);
END scanf(“%d”,&X);
printf(“\nEnter the second
value”);
scanf(“%d”,&y);
Z=X+Y ;
printf(“\nX+Y= %d”,Z);
return 0 ;
}

Note that the actions are flowing in a logical manner, that is, from top to bottom. There is no
branching and no process is repeated again. Each process is contributing something to the
next process.

IV.2 Selection (Decision)


Selection is a process of deciding which choice is made between two or more alternative
courses of action. Selection logic is depicted as an IF-THEN-ELSE-ENDIF or CASE-
ENDCASE structure. As the name suggests, in case of the IF-THEN-ELSE-ENDIF construct,
if the condition is true, the true alternative actions are performed and if condition is false,
then false alternative actions are performed on.

a) IF-THEN-ELSE-ENDIF construct

Flowchart Pseudocode C
• •
• •
• if(condition)
IFcondition THEN {
List of actions List of actions
ELSE }
List of different Else
actions {
ENDIF List of different
• actions
• }
• •

Topic: Introduction to programming10

Note that the ELSE keyword and 'Action 2' are optional. If the condition is true, Action 1 will
be performed; otherwise, Action 2 will be performed. In case you do not want to choose
between two alternate courses of actions, then simply use IF-THEN-ENDIF

Flowchart Pseudocode C
• •
• •
• •
IFcondition THEN if(condition)
List of actions {
ENDIF List of actions
• }
• •
• •

Hence, if the condition is true, then perform the list of actions listed in the IF-THEN-ENDIF
construct and then move on to the other actions in the process. In case the condition is false,
then move on to the rest of the actions in the process directly. Let us write a pseudocode to
find the largest of three numbers

Flowchart Pseudocode C
Topic: Introduction to programming11

START #include<stdio.h>
READ A, B, and C main()
IF A > B THEN {
IF A > C THEN int A, B, C;
DISPLAY A printf("Enter three integers: ");
ELSE scanf("%d%d%d",&A,&B,&C);
DISPLAY C if(A>B)
ENDIF if(A>C)
ELSE printf("\nThe greatest is %d",A);
IF B > C THEN else
DISPLAY B printf("\nThe greatest is %d",C);
ELSE else if (B>C)
DISPLAY C printf("\nThe greatest is %d",B);
ENDIF else
ENDIF printf("\nThe greatest is %d",C);
STOP return 0;
}

b) CASE-ENDCASE construct

From the above pseudocode you can see that the IF construct is nested into another IF
construct. However, if there are a number of conditions to be checked, then using multiple
IFs may look very clumsy. Hence, it is advisable to use the CASE-ENDCASE selection
construct for multipleway selection logic. A CASE construct indicates a multiway branch
based on many conditions. CASE construct uses four keywords, CASE, OF, OTHERS and
ENDCASE, along with conditions that are used to indicate the various alternatives.

Flowchart Pseudocode C
Topic: Introduction to programming12

CASE expression OF case (expression)


Condition 1: Sequence 1 {
Condition 2: Sequence 2 case value 1:
• Sequence 1;
• break ;
Condition n: Sequence n case value 2:
OTHERS : default sequence Sequence 2;
ENCASE break ;


case value n:
Sequence n;
break ;
default :
default sequence ;
}

CASE construct performs the same process as multiple IFs, but it is much easier to read and
write. The OTHERS clause, used with its default sequence, is optional and is used to perform
those actions, which do not satisfy any of the specified conditions. Conditions are normally
numbers or characters indicating the value of 'Expression'

Example:To assign points according to the grade

Flowchart Pseudocode C
READ Grade #include<stdio.h>
CASE Grade OF main(){
A : Points = 4 char grade;
B : Points = 3 int points;
C : Points = 2 printf("Enter the Grade ");
D : Points = 1 scanf("%c",&grade);
F : Points = 0 switch(grade) {
OTHERS : DISPLAY case 'A':points=4;
"Incorrect Grade" break;
ENDCASE case 'B':points=3;
DISPLAY points break;
STOP case 'C':points=2;
break;
case 'D':points=1;
break;
case 'E':points=0;
break;
default: printf("Incorrect
grade");
}
printf("points = %d",points);
return 0;
}

IV.3 Repetition (Looping)


Topic: Introduction to programming13

Looping construct is used when some particular task(s) is to be repeated for a number of
times according to the specified condition. By using looping, the programmer avoids
repeating the same set of instructions. In flowcharting, it is confusing to separate selection
from looping. This is because each structure uses the diamond (decision symbol) as their
control symbol. In pseudocode, we avoid this by using specific keywords, namely DO
WHILE-ENDDO and REPEAT-UNTIL, to designate looping

a) WHILE-ENDDO

In case of DO WHILE-ENDDO, the loop will continue as long as the condition is true. The
loop is entered only if the condition is true. The 'statement' is performed for each iteration. At
the conclusion of each iteration, the condition is evaluated and the loop continues as long as
the condition is true. The following pseudocode displays the first ten natural numbers using
the DO WHILE-ENDDO looping structure.

Flowchart Pseudocode C
WHILE condition is True while (condition)
statements {
ENDWHILE statements
}

Example:To display the first ten natural numbers using DO WHILE-ENDDO

Flowchart Pseudocode C
INITIALIZE Count to zero #include<stdio.h>
DO WHILE Count is greater than main()
or equal to 10 {
ADD 1 to Count int i=0;
PRINT Count while(i<10)
ENDDO {
STOP printf("%d ",i);
i++;
}
return 0;
}

After initializing the COUNT to zero, the loop construct begins. Since the value of COUNT
is less than 10, the condition stands true. Hence, the statements inside the loop structure are
Topic: Introduction to programming14

considered. In this structure, the value of COUNT is constantly increasing and as a result,
after certain point, that is, after 10 loops, the condition becomes untrue. Hence, the other
statements in the pseudocode are considered.

b) REPEAT-UNTIL

The REPEAT-UNTIL loop is similar to the DO WHILE-ENDDO, except that the test is
performed at the bottom of the loop instead of at the top

Flowchart Pseudocode C
Repeat Do
Statements {
Until condition is false
}
While (condition)

The 'statement' in this type of loop is always performed at least once, because the test is
performed after the statement is executed. At the end of each iteration, the condition is
evaluated, and the loop repeats until the condition gets true. The loop terminates when the
condition becomes true.

Example To display the first ten natural numbers using REPEAT-UNTIL

Flowchart Pseudocode C
INITIALIZE Count to zero #include<stdio.h>
REPEAT main()
ADD 1 to Count {
PRINT Count int i=0;
UNTIL Count is less than 10 do
STOP {
printf("%d ",i);
i++;
}
while(i<10);
return 0;
}

You might also like