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

Pseudocode and Flowchart 1 2

Uploaded by

an043973
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
617 views

Pseudocode and Flowchart 1 2

Uploaded by

an043973
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

2.

ALGORITHMS, FLOWCHARTS, DATA TYPES


AND PSEUDOCODE
2.1 ALGORITHMS

The term algorithm originally referred to any computation performed via a set of rules
applied to numbers written in decimal form. The word is derived from the phonetic
pronunciation of the last name of Abu Ja'far Mohammed ibn Musa al-Khowarizmi, who
was an Arabic mathematician who invented a set of rules for performing the four basic
arithmetic operations (addition, subtraction, multiplication and division) on decimal
numbers.

An algorithm is a representation of a solution to a problem. If a problem can be defined


as a difference between a desired situation and the current situation in which one is, then
a problem solution is a procedure, or method, for transforming the current situation to the
desired one. We solve many such trivial problems every day without even thinking about
it, for example making breakfast, travelling to the workplace etc. But the solution to such
problems requires little intellectual effort and is relatively unimportant. However, the
solution of a more interesting problem of more importance usually involves stating the
problem in an understandable form and communicating the solution to others. In the case
where a computer is part of the means of solving the problem, a procedure, explicitly
stating the steps leading to the solution, must be transmitted to the computer. This
concept of problem solution and communication makes the study of algorithms important
to computer science.

Throughout history, man has thought of ever more elegant ways of reducing the amount
of labour needed to do things. A computer has immense potential for saving time/energy,
as most (computational) tasks that are repetitive or can be generalised can be done by a
computer. For a computer to perform a desired task, a method for carrying out some
sequence of events, resulting in accomplishing the task, must somehow be described to
the computer. The algorithm can be described on many levels because the algorithm is
just the procedure of steps to take and get the result. The language used to describe an
algorithm to other people will be quite different from that which is used by the computer,
however the actual algorithm will in essence be the same. An example of an algorithm
people use would be a recipe to make a cake.

"4 extra large eggs, beaten


1&1/2 C. stock
1/2 teaspoon salt
1 scallion, minced
1 C. small shrimp or lobster flakes
1 t. soy sauce
1 Tablespoon oil
1. Mix all the ingredients, except the oil, in a deep bowl.

MT 512: Programming Design Page no: 6


2. Put 1" water in wide pot, then place deep bowl of batter inside.
3. Cover pot tightly and steam 15 min.
4. Heat oil very hot and pour over custard.
5. Steam 5 more min. Serves 4 people"

This breaks down 'Making Chinese egg custard' into smaller steps. To make the product
one still needs to know how to execute each of the steps in the procedure and understand
all of the terms.

Definition:
A procedure is a finite sequence of well-defined instructions, each of which can be
mechanically carried out in a finite amount of time.

The procedure must break up the problem solution into parts that the recipient party can
understand and execute. In the case of a computer, the problem solution is usually in the
form of a program that encompasses the algorithm and explains to the computer a clearly
defined procedure for achieving the solution. The procedure must consist of smaller steps
each of which the computers understand. There may be no ambiguities in the translation
of the procedure into the necessary action to be taken. A program is then just a specific
realisation of an algorithm, which may be executed on a physical device.

A computer is essentially a physical device designed to carry out a collection of primitive


actions. A procedure is a sequence of instructions written in terms of which evoke a
proper operation. To make effective use of an algorithm on a computer one must not only
find and understand a solution to the problem but also convey the algorithm to the
computer, giving the correct sequence of understood commands that represent the same
algorithm.

Definition:
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions)
which specify a finite sequence of operations that provides the solution to a problem, or
to a specific class of problems for any allowable set of input quantities (if there are
inputs). In other word, an algorithm is a step-by-step procedure to solve a given
problem

Alternatively, we can define an algorithm as a set or list of instructions for carrying out
some process step by step. A recipe in a cookbook is an excellent example of an
algorithm. The recipe includes the requirements for the cooking or ingredients and the
method of cooking them until you end up with a nice cooked dish.

In the same way, algorithms executed by a computer can combine millions of elementary
steps, such as additions and subtractions, into a complicated mathematical calculation.
Also by means of algorithms, a computer can control a manufacturing process or co-

MT 512: Programming Design Page no: 7


ordinate the reservations of an airline as they are received from the ticket offices all over
the country. Algorithms for such large-scale processes are, of course, very complex, but
they are built up from pieces.

One of the obstacles to overcome in using a computer to solve your problems is that of
translating the idea of the algorithm to computer code (program). People cannot normally
understand the actual machine code that the computer needs to run a program, so
programs are written in a programming language such as C or Pascal, which is then
converted into machine code for the computer to run.

In the problem-solving phase of computer programming, you will be designing


algorithms. This means that you will have to be conscious of the strategies you use to
solve problems in order to apply them to programming problems. These algorithms can
be designed though the use of flowcharts or pseudocode.

2.2 FLOWCHARTS

Flowcharting is a tool developed in the computer industry, for showing the steps
involved in a process. A flowchart is a diagram made up of boxes, diamonds and other
shapes, connected by arrows - each shape represents a step in the process, and the arrows
show the order in which they occur. Flowcharting combines symbols and flowlines, to
show figuratively the operation of an algorithm.

In computing, there are dozens of different symbols used in flowcharting (there are even
national and international flowcharting symbol standards). In business process analysis, a
couple of symbols are sufficient. A box with text inside indicates a step in the process,
while a diamond with text represents a decision point. See the figure for an example.

If the flowchart is too messy to draw, try starting again, but leaving out all of the decision
points and concentrating on the simplest possible course. Then the session can go back
and add the decision points later. It may also be useful to start by drawing a high-level
flowchart for the whole organisation, with each box being a complete process that has to
be filled out later.

From this common understanding can come a number of things - process improvement
ideas will often arise spontaneously during a flowcharting session. And after the session,
the facilitator can also draw up a written procedure - a flowcharting session is a good way
of documenting a process.

Process improvement starts with an understanding of the process, and flowcharting is the
first step towards process understanding.

MT 512: Programming Design Page no: 8


Flowcharting Symbols

There are 6 basic symbols commonly used in flowcharting of assembly language


programs: Terminal, Process, input/output, Decision, Connector and Predefined Process.
This is not a complete list of all the possible flowcharting symbols, it is the ones used
most often in the structure of Assembly language programming.

Symbol Name Function

Process Indicates any type of internal operation


inside the Processor or Memory

input/output Used for any Input / Output (I/O) operation.


Indicates that the computer is to obtain data
or output results

Decision Used to ask a question that can


be answered in a binary format (Yes/No,
True/False)

Connector Allows the flowchart to be drawn without


intersecting lines or without a reverse flow.

Predefined Process Used to invoke a subroutine or an


interrupt program.

Terminal Indicates the starting or ending of the


program, process, or interrupt program.

Flow Lines Shows direction of flow.

Generally, there are many standard flowcharting symbols.

General Rules for flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other
entry points. The exit point for all flowchart symbols is on the bottom except for
the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom
and one side.

MT 512: Programming Design Page no: 9


4. Generally a flowchart will flow from top to bottom. However, an upward flow
can be shown as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt
programs or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.

Flowcharting uses symbols that have been in use for a number of years to represent the
type of operations and/or processes being performed. The standardised format provides a
common method for people to visualise problems together in the same manner. The use
of standardised symbols makes the flow charts easier to interpret, however, standardising
symbols is not as important as the sequence of activities that make up the process.

Flowcharting Tips

• Chart the process the way it is really occurring. Do not document the way a written
process or a manager thinks the process happens.

• People typically modify existing processes to enable a more efficient process. If the
desired or theoretical process is charted, problems with the existing process will not
be recognised and no improvements can be made.

Note all circumstances actually dealt with.


• Test the flow chart by trying to follow the chart to perform the process charted. If
there is a problem performing the operation as charted, note any differences and
modify the chart to correct. A better approach would be to have someone unfamiliar
with the process try to follow the flow chart and note questions or problems found.

• Include mental steps in the process such as decisions. These steps are sometimes left
out because of familiarity with the process, however, represent sources of problems
due to a possible lack of information used to make the decision can be inadequate or
incorrect if performed by a different person.

Examples of Algorithms and Flowcharts

Example 1. Design an algorithm and the corresponding flowchart for adding the test
scores as given below:

26, 49, 98, 87, 62, 75

MT 512: Programming Design Page no: 10


a) Algorithm

1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop

b) The corresponding flowchart is as follows:

Start

Sum = 0

Get first testscore

Add First testscore


To sum

Get second testscore

Add second testscore


To sum

MT 512: Programming Design Page no: 11


1

Get third testscore

Add third testscore


to sum

Get Forth testscore

Add forth testscore


to sum

Get Fifth testscore

Add fifth testscore to sum

Get Six testscore

Add sixth testscore to


sum

Output Sum

STOP

The algorithm and the flowchart above illustrate the steps for solving the problem of
adding six testscores. Where one testscore is added to sum at a time. Both the algorithm
and flowchart should always have a Start step at the beginning of the algorithm or
flowchart and at least one stop step at the end, or anywhere in the algorithm or flowchart.
Since we want the sum of six testscore, then we should have a container for the resulting
sum. In this example, the container is called sum and we make sure that sum should start
with a zero value by step 2.

MT 512: Programming Design Page no: 12


Example 2: The problem with this algorithm is that, some of the steps appear more than
once, i.e. step 5 get second number, step 7, get third number, etc. One could shorten the
algorithm or flowchart as follows:

1. Start
2. Sum = 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop

Start

Sum =

Get a value

Sum = sum + value

Output

STOP

This algorithm and its corresponding flowchart are a bit shorter than the first one. In this
algorithm, step 3 to 5 will be repeated, where a number is obtained and added to sum.
Similarly the flowchart indicates a flowline being drawn back to the previous step
indicating that the portion of the flowchart is being repeated. One problem indicates that
these steps will be repeated endlessly, resulting in an endless algorithm or flowchart. The
algorithm needs to be improved to eliminate this problem. In order to solve this problem,
we need to add a last value to the list of numbers given. This value should be unique so
that, each time we get a value, we test the value to see if we have reached the last value.
In this way our algorithm will be a finite algorithm which ends in a finite number of steps
as shown below. There are many ways of making the algorithm finite.

The new list of numbers will be 26, 49, 498, 9387, 48962, 1, -1. The value –1 is a unique
number since all other numbers are positive.

1. Start
2. Sum = 0
3. Get a value

MT 512: Programming Design Page no: 13


4. If the value is equal to –1, go to step 7
5. Add to sum ( sum = sum + value)
6. Go to step 3 to get next Value
7. Output the sum
8. Stop

Corresponding flowchart

START

Sum = 0

Get a value

Value Yes
= -1

No

Sum = Sum + Value Output Sum

STOP

3. DATA TYPES

Although some contemporary languages allow programmers to invent his own data
types, and define their related operations, there are a number of traditional data types
found in most languages:

Integer
Integers are numeric data items, which are either positive or negative including zero, i.e.
1, 488, -22, 0, 456. Some programming languages put restrictions on the magnitude of
integers which may be used in program instructions. These restrictions are usually
dependent on the size of the memory location of the computer in which the language
may run.

MT 512: Programming Design Page no: 14


Real Numbers

There are two types of real numbers, Fixed-Point and Floating Point.

Fixed Point
Fixed point data items are numbers which have embedded decimal point i.e. 1.5,
458.4589, -0.569.

Floating Point
Floating point data items are numbers, which are, held as binary fractions by a computer.
The numbers are expressed in a form where you have a mantissa and an exponent, for
example

Number Mantissa Exponent


12.3 = 0.123 * 102 0.123 2
123000 = 0.123 * 106 0.123 6
0.000123 =0.123 * 10-3 0.123 -3

Floating point representation of data is used to overcome the restrictions placed on the
magnitude of numbers by the size of computer’s memory locations.

Character
Character data, sometimes referred to as “string” data, may consist of any digits, letters of
the alphabet or symbols which, the internal coding system of the computer is capable of
representing. Many programming languages require character data to be enclosed by
quotation marks when used in program instructions, for example PRINT “HAPPY NEW
YEAR”.

Boolean
Boolean data items are used as status indicators and may contain only one of two possible
values: True or False.

DATA ITEM
There are two basic methods of using data items in a program:

a) Constants
Data items are sometimes required to keep their values throughout the program, hence the
term constant. A constant is a specific value or character string used explicitly in an
operation. Consider the constant values 47.5, 1, and 13 in the example below.

Multiply … by 47.5
Add 1 to …
If … = 13
Print “PLEASE INPUT TODAY’S DATE”

MT 512: Programming Design Page no: 15


b) Variables and Variable names

A variable is a symbolic name assigned to a data item by the programmer. At any


particular time, a variable will stand for one particular data, called the value of a variable,
which may change from time to time during a computing process. The value of a variable
may change many times during the execution of a program. A variable is usually given a
name by the programmer.

Assignment

The assignment operation has the form:


variable := expression. (Pascal)
variable = expression. (C/C++/Java)

The assignment operation is used to assign a name to a value. Thus it is used whenever
you need to keep track of a value that is needed later. Some typical uses include:

• initialize a variable ( count = 0 )


• increment/decrement a counter ( count = count + 1 )
• accumulate values ( sum = sum + item )
• capture the result of a computation ( y = 3*x + 4 )
• swap two values ( t = x; x = y; y = t )

The assignment operator is not commute i.e. x = e is not the same as e = x. The variable
must be declared. Variables used in the expression must be defined (have values). The
type of the expression must be compatible with the type of the variable.

The order in which assignments are performed is important for example, if the first and
second assignments in the swap sequence were interchanged, x and y would end up
assigned to the same value. The input operation and the output operation share some of
the same constraints.

2.5 PSEUDOCODE
Pseudocode is one of the tools that can be used to write a preliminary plan that can be
developed into a computer program. Pseudocode is a generic way of describing an
algorithm without use of any specific programming language syntax. It is, as the name
suggests, pseudo code —it cannot be executed on a real computer, but it models and
resembles real programming code, and is written at roughly the same level of detail.

Pseudocode, by nature, exists in various forms, although most borrow syntax from
popular programming languages (like C, Lisp, or FORTRAN). Natural language is used
whenever details are unimportant or distracting.

MT 512: Programming Design Page no: 16


Computer science textbooks often use pseudocode in their examples so that all
programmers can understand them, even if they do not all know the same programming
languages. Since pseudocode style varies from author to author, there is usually an
accompanying introduction explaining the syntax used.

In the algorithm design, the steps of the algorithm are written in free English text and,
although brevity is desired, they may be as long as needed to describe the particular
operation. The steps of an algorithm are said to be written in pseudocode.

Many languages, such as Pascal, have a syntax that is almost identical to pseudocode and
hence make the transition from design to coding extremely easy.

The following section deal with the control structures (control constructs) Sequence,
Selection and Iteration or Repetition.

CONTROL STRUCTURES OR LOGICAL STRUCTURES


The key to better algorithm design and thus to programming lies in limiting the control
structure to only three constructs. These are illustrated below:

The sequence structure


The first type of control structures is called the sequence structure. This structure is the
most elementary structure. The sequence structure is a case where the steps in an
algorithm are constructed in such a way that, no condition step is required. The sequence
structure is the logical equivalent of a straight line.

For example, suppose you are required to design an algorithm for finding the average of
six numbers, and the sum of the numbers is given. The pseudocode will be as follows

Start
Get the sum
Average = sum / 6
Output the average
Stop

The corresponding flowchart will appear as follows:

MT 512: Programming Design Page no: 17


Start

Get the sum

Average = sum/6

Output sum

Stop

Example 3: This is the pseudo-code required to input three numbers from the keyboard
and output the result.

Use variables: sum, number1, number2, number3 of type integer


Accept number1, number2, number3
Sum = number1 + number2 + number3
Print sum
End program

Example 4: The following pseudo-code describes an algorithm which will accept two
numbers from the keyboard and calculate the sum and product displaying the answer on
the monitor screen.

Use variables sum, product, number1, number2 of type real


display “Input two numbers”
accept number1, number2
sum = number1 + number2
print “The sum is “, sum
product = number1 * number2
print “The Product is “, product
end program

Decision Structure or Selection Structure

The decision structure or mostly commonly known as a selection structure, is case where
in the algorithm, one has to make a choice of two alternatives by making decision
depending on a given condition.

MT 512: Programming Design Page no: 18


Selection structures are also called case selection structures when there are two or more
alternatives to choose from.

This structure can be illustrated in a flowchart as follows:

True Condition False

Task-A Task-B

In pseudocode form we get

If condition is true
Then do task A
else
Do Task-B

In this example, the condition is evaluated, if the condition is true Task-A is evaluated
and if it is false, then Task-B is executed.

A variation of the construct of the above figure is shown below

False
Condition

True

Task-A

From the above structure, we have the following

MT 512: Programming Design Page no: 19


If condition is true then
Do Task-A

In this case, if condition is false, nothing happens. Otherwise Task-A is executed.

The selection requires the following


• Choose alternative actions as a result of testing a logical condition
• Produce code to test a sequence of logical tests

Making Choices

There are many occasions where a program is required to take alternative actions. For
example, there are occasions where we need to take action according to the user choice.
All computer languages provide a means of selection. Usually it is in the form of If
statement and our pseudo-code is no exception to this.

We will use the if statement together with logical operators to test for true or false as
shown below.

If a = b
print “a = b”

The action is only taken when the test is true.

The logical operators used in our pseudo-code are


= is equal to
> is greater than
< is less than
>= is greater than or equal
<= is less than or equal
<> is not eaqual to

Example 5: The following shows how the selection control structure is used in a program
where a user chooses the options for multiplying the numbers or adding them or
subtracting.

Use variables: choice, of the type character


ans, number1, number2, of type integer
display “choose one of the following”
display “m for multiply”
display “a for add”
display “s for subtract”
accept choice
display “input two numbers you want to use”
accept number1, number2

MT 512: Programming Design Page no: 20


if choice = m then ans = number1 * number2
if choice = a then ans = number1 + number2
if choice = s then ans = number1 - number2
display ans

Compound Logical Operators


There are many occasions when we need to extend the conditions that are to be tested.
Often there are conditions to be linked.

In everyday language we say things like If I had the time and the money I would go on
holiday. The and means that both conditions must be true before we take an action. We
might also say I am happy to go to the theatre or the cinema. The logical link this time
is or . Conditions in if statements are linked in the same way. Conditions linked with and
only result in an action when all conditions are true. For example, if a >b and a > c then
display “a is the largest”. Conditions linked with an or lead to an action when either or
both are true.

Example 6: The program is to input a examination mark and test it for the award of a
grade. The mark is a whole number between 1 and 100. Grades are awarded according to
the following criteria:

>= 80 Distinction
>= 60 Merit
>= 40 Pass
< 40 fail

The pseudo-code is

Use variables: mark of type integer


If mark >= 80 display “distinction”
If mark >= 60 and mark < 80 display “merit”
If mark >= 40 and mark < 60 display “pass”
If mark < 40 display “fail”

An if statement on its own is often not the best way of solving problems. A more elegant
set of conditions can be created by adding an else statement to the if statement. The else
statement is used to deal with situations as shown in the following examples.

Example 7: A person is paid at top for category 1 work otherwise pay is at normal rate.

If the work is category 1


pay-rate is top
Else
pay-rate is normal

MT 512: Programming Design Page no: 21


The else statement provides a neat way of dealing with alternative condition. In pseudo-
code we write

If work = cat1 then p-rate: = top


Else p-rate = normal
Or
If work = cat1 then
p-rate: = top
Else
p-rate = normal

The following example illustrate the use of if … else statements in implementing double
alternative conditions.

If salary < 50000 then


Tax = 0
Else
If salary > 50000 AND salary < 100000 then
Tax = 50000 * 0.05
Else
Tax = 100000 * 0.30
The case statement
Repeating the if … else statements a number of times can be somewhat confusing. An
alternative method provided in a number of languages is to use a selector determined by
the alternative conditions that are needed. In our pseudo-code, this will called a case
statement.

Example 8: The following program segment outputs a message to the monitor screen
describing the insurance available according to a category input by the user.

Use variables: category of type character


Display “input category”
Accept category
If category = U
Display “insurance is not available”
Else
If category = A then
Display “insurance is double”
Else
If category = B then
Display “insurance is normal”
Else
If category = M then
Display “insurance is medically dependent”
Else
Display “entry invalid”

MT 512: Programming Design Page no: 22


This can be expressed in a case statement as follows:
Use variables: category of type character
Display “input category”
Accept category
DO case of category
CASE category = U
Display “insurance not available”
CASE category = A
Display “insurance is double”
CASE category = B
Display “insurance is normal”
CASE category = M
Display “insurance is medically dependent”
OTHERWISE
Display “entry is invalid”
ENDCASE
Instead of using the word otherwise, one can use else.

Repetition or Iteration Structure


A third structure causes the certain steps to be repeated.

Condition False

True

Task

The Repetition structure can be implemented using


• Repeat Until Loop
• The While Loop
• The For Loop

Any program instruction that repeats some statement or sequence of statements a number
of times is called an iteration or a loop. The commands used to create iterations or loops

MT 512: Programming Design Page no: 23


are all based on logical tests. There three constructs for iterations or loops in our pseudo-
code.

The Repeat Until loop.


The syntax is
REPEAT
A statement or block of statements
UNTIL a true condition

Example 9: A program segment repeatedly asks for entry of a number in the range 1 to
100 until a valid number is entered.

REPEAT
DISPLAY “Enter a number between 1 and 100”
ACCEPT number
UNTIL number < 1 OR number > 100

Example 10. A survey has been carried out to discover the most popular sport. The
results will be typed into the computer for analysis. Write a program to accomplish this.

REPEAT
DISPLAY “Type in the letter chosen or Q to finish”
DISPLAY “A: Athletics”
DISPLAY “S: Swimming”
DISPLAY “F: Football”
DISPLAY “B: Badminton”
DISPLAY “Enter data”
ACCEPT letter
If letter = ‘A’ then
Athletics = athletics + 1
If letter = ‘S’ then
Swimming = Swimming + 1
If letter = ‘F’ then
Football = Football + 1
If letter = ‘B’ then
Badminton = Badminton + 1
UNTIL letter = ‘Q’
DISLAY “Athletics scored”, athletics, “votes”
DISLAY “Swimming scored”, swimming, “votes”
DISLAY “Football scored”, football, “votes”
DISLAY “Badminton scored”, Badminton, “votes”

The WHILE loop


The second type of iteration we will look at is the while iteration. This type of conditional
loop tests for terminating condition at the beginning of the loop. In this case no action is
performed at all if the first test causes the terminating condition to evaluate as false.

MT 512: Programming Design Page no: 24


The syntax is
WHILE (a condition is true)
A statement or block of statements
ENDWHILE

Example 11: A program segment to print out each character typed at a keyboard until the
character ‘q’ is entered.
WHILE letter <> ‘q’
ACCEPT letter
DISPLAY “The character you typed is”, letter
ENDWHILE
Example 12: Write a program that will output the square root of any number input until
the number input is zero.

In some cases, a variable has to be initialised before execution of the loop as shown in
the following example.
Use variable: number of type real
DISPLAY “Type in a number or zero to stop”
ACCEPT number
WHILE number <> 0
Square = number * number
DISPLAY “The square of the number is”, square
DISPLAY “Type in a number or zero to stop”
ACCEPT number
ENDWHILE

The FOR Loop


The third type of iteration, which we shall use when the number of iterations is known in
advance, is a for loop. This, in its simplest form, uses an initialisation of the variable as a
starting point, a stop condition depending on the value of the variable. The variable is
incremented on each iteration until it reaches the required value.

The pseudo-code syntax will be:


FOR (starting state, stopping condition, increment)
Statements
ENDFOR
Example 13.
FOR (n = 1, n <= 4, n + 1)
DISPLAY “loop”, n
ENDFOR
The fragment of code will produce the output

Loop 1
Loop 2
Loop 3
Loop 4

MT 512: Programming Design Page no: 25


In the example, n is usually referred as the loop variable, or counting variable, or index of
the loop. The loop variable can be used in any statement of the loop. The variable should
not be assigned a new value within the loop, which may change the behaviour of the
loop.

Example 14: Write a program to calculate the sum and average of a series of numbers.
The pseudo-code solution is:
Use variables: n, count of the type integer
Sum, number, average of the type real
DISPLAY “How many numbers do you want to input”
ACCEPT count
SUM = 0
FOR (n = 1, n <= count, n + 1)
DISPLAY “Input the number from your list”
ACCEPT number
SUM = sum + number
ENDFOR
Average = sum / count
DISPLAY “The sum of the numbers is “, sum
DISPLAY “Average of the numbers is “, average

Flowcharts have been used in this section to illustrate the nature of the three control
structures. These three are the basic control structures out of which all programs are built.
Beyond this, flowcharts serve the programmer in two distinct ways: as problem solving
tools and as tools for documenting a program.

Example
Design an algorithm and the corresponding flowchart for finding the sum of n numbers.

Pseudocode Program
Start
Sum = 0
Display “Input value n”
Input n
For(I = 1, n, 5)
Input a value
Sum = sum + value
ENDFOR
Output sum
Stop
In this example, we have used I to allow us to count the numbers, which we get for the
addition. We compare I with n to check whether we have exhausted the numbers or not in
order to stop the computation of the sum (or to stop the iteration structure). In such a
case, I is referred to as a counter.

MT 512: Programming Design Page no: 26


The corresponding flowchart will be as follows:

Start

Sum = 0

I=1

Input a number

True
I>n

False Output Sum


Sum = sum + number
Stop

I=I+1

Exercise
1. Design an algorithm and the corresponding flowchart for finding the sum of
the numbers 2, 4, 6, 8, …, n

2. Using flowcharts, write an algorithm to read 100 numbers and then display the
sum.
3. Write an algorithm to read two numbers then display the largest.
4. Write an algorithm to read two numbers then display the smallest
5. Write an algorithm to read three numbers then display the largest.
6. Write an algorithm to read 100 numbers then display the largest.

MT 512: Programming Design Page no: 27


Algorithm & Flowchart Manual

ALGORITHM & FLOWCHART MANUAL


for
STUDENTS

(Ravi K. Walia)
Assistant Professor & Incharge
Computer & Instrumentation Centre
Dr. Y. S. Parmar University of Horticulture & Forestry,
Nauni Solan INDIA (HP)

1 CIC-UHF
Algorithm & Flowchart Manual

PREFACE

This document has been prepared for students at Dr. Y. S. Parmar University of Horticulture
& Forestry, Nauni, Solan (HP) India. Software Engineer uses various programming
languages to create programs. Before writing a program, first needs to find a procedure for
solving the problem. The program written without proper pre-planning has higher chances of
errors.

Algorithm and flowchart are the powerful tools for learning programming. An algorithm is a
step-by-step analysis of the process, while a flowchart explains the steps of a program in a
graphical way. Algorithm and flowcharts helps to clarify all the steps for solving the problem.
For beginners, it is always recommended to first write algorithm and draw flowchart for
solving a problem and then only write the program.

Beginners find it difficult to write algorithm and draw flowchart. The algorithm can vary from
person to person to solve a particular problem. The manual will be useful for the students to
learn algorithm and flowchart. It includes basics of algorithm and flowchart along with
number of examples. Software ClickCharts by NCH (unlicensed version) has been used to
draw all the flowcharts in the manual.

2 CIC-UHF
Algorithm & Flowchart Manual
..

ALGORITHM:

The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means
a procedure or a technique. Software Engineer commonly uses an algorithm for planning
and solving the problems. An algorithm is a sequence of steps to solve a particular problem
or algorithm is an ordered set of unambiguous steps that produces a result and terminates in
a finite time

Algorithm has the following characteristics

• Input: An algorithm may or may not require input

• Output: Each algorithm is expected to produce at least one result

• Definiteness: Each instruction must be clear and unambiguous.

• Finiteness: If the instructions of an algorithm are executed, the algorithm


should terminate after finite number of steps

The algorithm and flowchart include following three types of control structures.

1. Sequence: In the sequence structure, statements are placed one after the other and
the execution takes place starting from up to down.
2. Branching (Selection): In branch control, there is a condition and according to a
condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one
of the two branches is explored; but in the case of FALSE condition, the other
alternative is taken. Generally, the ‘IF-THEN’ is used to represent branch control.
3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed
repeatedly based on certain loop condition e.g. WHILE, FOR loops.

Advantages of algorithm

• It is a step-wise representation of a solution to a given problem, which makes it easy


to understand.
• An algorithm uses a definite procedure.
• It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
• Every step in an algorithm has its own logical sequence so it is easy to debug.

3 CIC-UHF
Algorithm & Flowchart Manual

HOW TO WRITE ALGORITHMS

Step 1 Define your algorithms input: Many algorithms take in data to be processed, e.g.
to calculate the area of rectangle input may be the rectangle height and rectangle width.

Step 2 Define the variables: Algorithm's variables allow you to use it for more than one
place. We can define two variables for rectangle height and rectangle width as HEIGHT and
WIDTH (or H & W). We should use meaningful variable name e.g. instead of using H & W
use HEIGHT and WIDTH as variable name.

Step 3 Outline the algorithm's operations: Use input variable for computation purpose,
e.g. to find area of rectangle multiply the HEIGHT and WIDTH variable and store the value in
new variable (say) AREA. An algorithm's operations can take the form of multiple steps and
even branch, depending on the value of the input variables.

Step 4 Output the results of your algorithm's operations: In case of area of rectangle
output will be the value stored in variable AREA. if the input variables described a rectangle
with a HEIGHT of 2 and a WIDTH of 3, the algorithm would output the value of 6.

FLOWCHART:

The first design of flowchart goes back to 1945 which was designed by John Von Neumann.
Unlike an algorithm, Flowchart uses different symbols to design a solution to a problem. It is
another commonly used programming tool. By looking at a Flowchartone can understand the
operations and sequence of operations performed in a system. Flowchart is often considered
as a blueprint of a design used for solving a specific problem.

Advantages of flowchart:

• Flowchart is an excellent way of communicating the logic of a program.


• Easy and efficient to analyze problem using flowchart.
• During program development cycle, the flowchart plays the role of a blueprint, which
makes program development process easier.
• After successful development of a program, it needs continuous timely maintenance
during the course of its operation. The flowchart makes program or system
maintenance easier.
• It is easy to convert the flowchart into any programming language code.

4 CIC-UHF
Algorithm & Flowchart Manual

Flowchart is diagrammatic /Graphical representation of sequence of steps to solve a


problem. To draw a flowchart following standard symbols are use

Symbol Name Symbol function

Used to represent start and


Oval end of flowchart

Used for input and output


Parallelogram
operation

Processing: Used for


Rectangle arithmetic operations and
data-manipulations

Decision making. Used to


represent the operation in
Diamond which there are two/three
alternatives, true and false
etc

Flow line Used to indicate


Arrows the flow of logic by
connecting symbols

Circle Page Connector

Off Page Connector

Predefined Process
/Function Used to represent
a group of statements
performing one processing
task.

Preprocessor

|--------------
--------- | Comments
|--------------

5 CIC-UHF
Algorithm & Flowchart Manual

The language used to write algorithm is simple and similar to day-to-day life language. The
variable names are used to store the values. The value store in variable can change in the
solution steps. In addition some special symbols are used as below

Assignment Symbol (  or =) is used to assign value to the variable.

e.g. to assign value 5 to the variable HEIGHT, statement is

HEIGHT  5

or

HEIGHT = 5

The symbol ‘=’ is used in most of the programming language as an assignment symbol, the
same has been used in all the algorithms and flowcharts in the manual.

The statement C = A + B means that add the value stored in variable A and variable B
then assign/store the value in variable C.

The statement R = R + 1 means that add I to the value stored in variable R and then
assign/store the new value in variable R, in other words increase the value of variable R by 1

Mathematical Operators:

Operator Meaning Example


+ Addition A+B
- Subtraction A–B
* Multiplication A*B
/ Division A/ B
^ Power A^3 for A3
% Reminder A%B

Relational Operators

Operator Meaning Example


< Less than A<B
<= Less than or equal to A <= B
= or == Equal to A = B
# or != Not equal to A # B or A !=B
> Greater than A>B
>= Greater tha or equal to A >= B

6 CIC-UHF
Algorithm & Flowchart Manual

Logical Operators

Operator Example Meaning


AND A < B AND B < C Result is True if both A<B and
B<C are true else false
OR A< B OR B < C Result is True if either A<B or
B<C are true else false
NOT NOT (A >B) Result is True if A>B is false
else true

Selection control Statements

Selection Control Example Meaning


IF ( Condition ) Then IF ( X > 10 ) THEN If condition X>10 is True
… Y=Y+5 execute the statement
ENDIF ENDIF between THEN and ENDIF

IF ( Condition ) Then IF ( X > 10 ) THEN If condition X>10 is True


… Y=Y+5 execute the statement
ELSE ELSE between THEN and ELSE
….. Y=Y+8 otherwise execute the
Z=Z+3 statements between ELSE
ENDIF ENDIF and ENDIF

Loop control Statements

Selection Control Example Meaning


WHILE (Condition) WHILE ( X < 10) Execute the loop as long as
DO DO the condition is TRUE
.. print x
.. x=x+1
ENDDO ENDDO
DO DO Execute the loop as long as
…. print x the condition is false
… x=x+1
UNTILL (Condition) UNTILL ( X >10)

GO TO statement also called unconditional transfer of control statement is used to transfer


control of execution to another step/statement. . e.g. the statement GOTO n will transfer
control to step/statement n.

Note: We can use keyword INPUT or READ or GET to accept input(s) /value(s) and
keywords PRINT or WRITE or DISPLAY to output the result(s).

7 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the sum of two numbers

Algorithm

Step-1 Start

Step-2 Input first numbers say A

Step-3 Input second number say B

Step-4 SUM = A + B

Step-5 Display SUM

Step-6 Stop

OR

Algorithm

Step-1 Start

Step-2 Input two numbers say A & B

Step-3 SUM = A + B

Step-4 Display SUM

Step-5 Stop

8 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to convert temperature from Celsius to Fahrenheit

C : temperature in Celsius
F : temperature Fahrenheit

Algorithm

Step-1 Start

Step-2 Input temperature in Celsius say C

Step-3 F = (9.0/5.0 x C) + 32

Step-4 Display Temperature in Fahrenheit F

Step-5 Stop

Algorithm & Flowchart to convert temperature from Fahrenheit to Celsius

C : temperature in Celsius
F : temperature Fahrenheit

Algorithm

Step-1 Start

Step-2 Input temperature in Fahrenheit say F

Step-3 C = 5.0/9.0 (F - 32 )

Step-4 Display Temperature in Celsius C

Step-5 Stop

9 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Area and Perimeter of Square

L : Side Length of Square


AREA : Area of Square
PERIMETER : Perimeter of Square

Algorithm

Step-1 Start

Step-2 Input Side Length of Square say L

Step-3 Area = L x L

Step-4 PERIMETER = 4 x L

Step-5 Display AREA, PERIMETER

Step-6 Stop

Algorithm & Flowchart to find Area and Perimeter of Rectangle

L : Length of Rectangle
B : Breadth of Rectangle
AREA : Area of Rectangle
PERIMETER : Perimeter of Rectangle

Algorithm

Step-1 Start

Step-2 Input Side Length & Breadth say L, B

Step-3 Area = L x B

Step-4 PERIMETER = 2 x ( L + B)

Step-5 Display AREA, PERIMETER

Step-6 Stop

10 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Area and Perimeter of Circle

R : Radius of Circle
AREA : Area of Circle Start

PERIMETER : Perimeter of Circle

Input Value
Algorithm of R

Step-1 Start
AREA = 22.0/7.0
Step-2 Input Radius of Circle say R xRx R

Step-3 Area = 22.0/7.0 x R x R


PERIMTER = 2 X
22.0/7.0 x R
Step-4 PERIMETER = 2 x 22.0/7.0 x R

Step-5 Display AREA, PERIMETER


Pr int A REA,
Step-6 Stop PER I M T ER

Stop

Algorithm & Flowchart to find Area & Perimeter of Triangle


(when three sides are given)

A : First Side of Triangle


B : Second Side of Triangle
C : Third Side of Triangle
AREA : Area of Triangle
PERIMETER : Perimeter of Triangle

Algorithm

Step-1 Start

Step-2 Input Sides of Triangle A,B,C

Step-3 S= (A + B + C)/ 2.0

Step-4 AREA = SQRT(S x (S-A) x (S-B) x(S-C))

Step-5 PERIMETER = S1 + S2 + S3

Step-6 Display AREA, PERIMETER

Step-7 Stop

11 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Simple Interest

P : Principle Amount
N : Time in Years
R : % Annual Rate of Interest
SI : Simple Interest

Algorithm

Step-1 Start

Step-2 Input value of P, N, R

Step-3 SI = (P x N x R)/100.0

Step-4 Display SI F

Step-6 Stop

Algorithm & Flowchart to find Compound Interest

P : Principle Amount
N : Time in Years
R : % Annual Rate of Interest
CI : Compound Interest

Algorithm

Step-1 Start

Step-2 Input value of P, N, R C

Step-3 CI = P(1+R/100)N - P

Step-4 Display CI

Step-6 Stop

..

12 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to Swap Two Numbers using Temporary Variable

Algorithm

Step-1 Start

Step-2 Input Two Numbers Say NUM1,NUM2

Step-3 Display Before Swap Values NUM1, NUM2

Step-4 TEMP = NUM1

Step-5 NUM1 = NUM2

Step-6 NUM2 = NUM1

Step-7 Display After Swap Values NUM1,NUM

Step-8 Stop

Algorithm & Flowchart to Swap Two Numbers without using temporary


variable

Algorithm

Step-1 Start

Step-2 Input Two Numbers Say A,B

Step-3 Display Before Swap Values A, B

Step-4 A=A+B

Step-5 B=A-B

Step-6 A=A-B

Step-7 Display After Swap Values A, B

Step-8 Stop

13 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the smallest of two numbers

Algorithm

Step-1 Start

Step-2 Input two numbers say

NUM1,NUM2

Step-3 IF NUM1 < NUM2 THEN

print smallest is NUM1

ELSE

print smallest is NUM2

ENDIF

Step-4 Stop

Algorithm & Flowchart to find the largest of two numbers

Algorithm
Start
Step-1 Start

Step-2 Input two numbers say


I nput V alue
NUM1,NUM2 of NUM1

Step-3 IF NUM1 > NUM2 THEN

print largest is NUM1 Input Value


of NUM2
ELSE

print largest is NUM2 Print Yes if No Print


Largest is NUM1 > NUM2
Largest is
NUM1 NUM2
ENDIF

Step-4 Stop

Stop

14 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the largest of three numbers

Algorithm

Step-1 Start

Step-2 Read three numbers say num1,num2, num3

Step-3 if num1>num2 then go to step-5

Step-4 IF num2>num3 THEN


print num2 is largest
ELSE
print num3 is largest
ENDIF
GO TO Step-6
Step-5 IF num1>num3 THEN
print num1 is largest
ELSE
print num3 is largest
ENDIF
Step-6 Stop

15 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the largest of three numbers (an another way)

Algorithm

Step-1 Start

Step-2 Read three numbers say A,B,C

Step-3 BIG = A

Step-4 IF B > BIG THEN

BIG = B

ENDIF

Step-5 IF C >BIG THEN

BIG = C

ENDIF

Step-6 Write BIG

Step-7 Stop

16 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Even number between 1 to 50

Algorithm

Step-1 Start

Step-2 I=1

Step-3 IF (I >50) THEN


GO TO Step-7
ENDIF
Step-4 IF ( (I % 2) =0) THEN
Display I
ENDIF
Step-5 I=I+1

Step-6 GO TO Step--3

Step-7 Stop

Algorithm & Flowchart to find Odd numbers between 1 to n where n is a


positive Integer

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 I=1

Step-4 IF (I >N) THEN


GO TO Step-8
ENDIF
Step-5 IF ( (I % 2)=1) THEN
Display I
ENDIF
Step-6 I=I+1

Step-7 GO TO Step-4

Step-8 Stop

17 CIC-UHF
Algorithm & Flowchart Manual

..

Algorithm & Flowchart to find sum of series 1+2+3+…..+N

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 I = 1, SUM=0

Step-4 IF (I >N) THEN


GO TO Step-8
ENDIF
Step-5 SUM = SUM + I

Step-6 I=I+1

Step-7 Go to step-4

Step-8 Display value of SUM

Step-9 Stop

Algorithm & Flowchart to find sum of series 1+3+5+…..+N, Where N is positive


odd Integer
Algorithm

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 I = 1, SUM=0

Step-4 IF (I >N) THEN


GO TO step 8
ENDIF
Step-5 SUM = SUM + I

Step-6 I=I+2

Step-7 Go to step-4

Step-8 Display value of SUM

Step-9 Stop

18 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find sum of series 1 – X + X2 –X3 ….XN

Algorithm

Step-1 Start

Step-2 Input Value of N, X

Step-3 I = 1, SUM=1, TERM=1

Step-4 IF (I >N) THEN


GO TO Step-9
ENDIF
Step-5 TERM = - TERM * X

Step-6 SUM = SUM + TERM

Step-7 I=I+1

Step-8 Go to step-4

Step-9 Display value of SUM

Step-10 Stop

Algorithm & Flowchart to print multiplication Table of a number

Algorithm

Step-1 Start

Step-2 Input Value of NUM

Step-3 I=1

Step-4 IF (I >10) THEN


GO TO Step 9
ENDIF
Step-5 PROD = NUM * I

Step-6 WRITE I “x” NUM “=” PROD

Step-7 I=I+1

Step-8 Go to step-4

Step-9 Stop

19 CIC-UHF
Algorithm & Flowchart Manual

..

Algorithm & Flowchart to generate first n Fibonacci terms 0,1,1,2,3,5…n (n>2)

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 A=0, B=1, COUNT=2

Step-4 WRITE A, B

Step-5 IF (COUNT >N) then go to step 12

Step-6 NEXT= A + B

Step-7 WRITE NEXT

Step-8 A=B

Step-9 B=NEXT

Step-10 COUNT=COUNT + 1

Step-11 Go to step-4

Step-12 Stop

20 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find sum and average of given series of numbers

Algorithm

Step-1 Start

Step-2 COUNT=0

Step-3 SUM=0

Step-4 Input NUM (next number in series)

Step-5 SUM= SUM +NUM

Step-6 COUNT=COUNT+1

Step-7 IF More Number in Series then

GOTO Step-4

ENDIF

Step-8 AVERGAE=SUM / COUNT

Step-9 WRITE SUM, AVERAGE

Step-10 Stop

21 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Roots of Quadratic Equations AX2+BX+C=0

Algorithm

Step-1 Start

Step-2 Input A,B,C

Step-3 DISC= B2 – 4 A * C

Step-4 IF (DISC < 0) THEN


Write Roots are Imaginary
Stop
ENDIF
Step-5 IF (DISC==0) THEN
Write Roots are Real and Equal
X1 = - B/(2*A)
Write Roots are X1,X1
Stop
ENDIF
Step-6 IF (DISC >0)

Write Roots are Real and Unequal

X1= (- B + SQRT(DISC)) / (2*A)

X2= (- B + SQRT(DISC)) / (2*A)

Write Roots are X1,X2

Stop

ENDIF

22 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find if a number is prime or not

Algorithm

Step-1 Start

Step-2 Input NUM

Step-3 R=SQRT(NUM)

Step-4 I=2

Step-5 IF ( I > R) THEN


Write NUM is Prime Number
Stop
ENDIF
Step 6 IF ( NUM % I ==0) THEN
Write NUM is Not Prime
Stop
ENDIF
Step-7 I=I+1

Step-8 Go to Step-5

23 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find GCD and LCM of two numbers

Algorithm

Step-1 Start

Step-2 Read two number A, B

Step-3 IF (A > B) THEN


N =A
D=B
ELSE
N=B
D=A
ENDIF
Step-4 r=N/D

Step-5 WHILE (r != 0)
DO
N=D
D=r
r =N%D
DONE

Step-6 gcd=d
Step-7 lcm = (a*b)/gcd

Step-8 Display gcd, lcm

Step-9 Stop

24 CIC-UHF
Algorithm & Flowchart Manual

Algorithm & Flowchart to find Factorial of number n ( n!=1x2x3x…n)

Algorithm

Step-1 Start

Step-2 Read number N

Step-3 FACT=1 CTRL=1


Step-4 WHILE (CTRL <= N)
DO
FACT=FACT*I
CTRL=CTRL+1
DONE
Step-5 Display FACT

Step-6 Stop

Algorithm & Flowchart to find all the divisor of a number

Algorithm

Step-1 Start

Step-2 Read number N

Step-3 D=1
Step-4 WHILE (D< N)
DO
IF ( N % D ==0) THEN
PRINT D
ENDIF
D=D+1
DONE
Step-5 Stop

25 CIC-UHF
Flow Chart and Pseudo Code

© Dr. Jyoti Lakhani


The American National Standards Institute (ANSI) set standards for
flowcharts and their symbols in the 1960s.

The International Organization for Standardization (ISO) adopted the


ANSI symbols in 1970.

The current standard, ISO 5807, was revised in 1985.

Generally, flowcharts flow from top to bottom and left to right.

© Dr. Jyoti Lakhani


What is a Flowchart?

A flowchart is a graphical representations of steps of an Algorithm and


programming logic

Flowchart Symbols

Terminator The terminator symbol represents the starting or


ending point of the system.

Process A box indicates some particular operation.

© Dr. Jyoti Lakhani


Document This represents a printout, such as a
document or a report.

Decision A diamond represents a decision or branching


point. Lines coming out from the diamond
indicates different possible situations, leading
to different sub-processes.

It represents information entering or leaving


Data the system. An input might be an order from a
customer. Output can be a product to be
delivered.

Lines represent the flow of the sequence and


Flow direction of a process.

© Dr. Jyoti Lakhani


On-Page Reference This symbol would contain a letter inside. It
indicates that the flow continues on a
matching symbol containing the same letter
somewhere else on the same page.

This symbol would contain a letter inside. It


Off-Page Reference indicates that the flow continues on a
matching symbol containing the same letter
somewhere else on a different page.

Delay or Bottleneck Identifies a delay or a bottleneck.

© Dr. Jyoti Lakhani


Indicating additional information about a step
in the program. Represented as an open
Annotation rectangle with a dashed or solid line
connecting it to the corresponding symbol in
the flowchart

Shows named process which is defined


Predefined Process elsewhere. Represented as a rectangle
with double-struck vertical edges

Data File or
Database

Single documents

Multiple documents
© Dr. Jyoti Lakhani
Manual operation

Manual input

Preparation or Initialization

© Dr. Jyoti Lakhani


© Dr. Jyoti Lakhani
Calculate Profit and Loss

© Dr. Jyoti Lakhani


Draw a flowchart to input two numbers from
user and display the largest of two numbers

© Dr. Jyoti Lakhani


Download, Install and Practice

http://flowgorithm.org/download/index.htm

© Dr. Jyoti Lakhani


An example of Algorithm

Algorithm to add two numeric values

1. Declare two variables n1 and n2


2. Read values in n1 and n2
3. Declare one more variable sum
4. Add n1 and n2 and assign result in sum
5. Print sum

General English

© Dr. Jyoti Lakhani


Algorithm to add two numeric values

Start

Input n1
Input n2

Sum = n1 + n2

Print Sum

End

Flow Chart Implementation


© Dr. Jyoti Lakhani
Algorithm to add two numeric values

Algorithm Name: Add_Numbers ( n1, n2)


Input: Two integers n1 and n2
Output: sum of n1 and n2

Start
1. sum <- n1 + n2
2. Print sum
End

Pseudo Code Implementation

© Dr. Jyoti Lakhani


WHY? Algorithms will often be expressed in pseudo code

WHAT? A mixture of code and English

Pseudo code is a simple way of writing programming code in English

Pseudo code is simply an implementation of an algorithm in the form of


annotations and informative text written in plain English.

Pseudo code is not actual programming language

It has no syntax like any of the programming language and thus can’t
be compiled or interpreted by the computer.

“While understanding pseudo code is usually not difficult, writing it can be


a challenge” © Dr. Jyoti Lakhani
Why use pseudo code at all?
If we write an algorithm in English,
the description may be at so high a level that it is
difficult to analyze the algorithm and to transform
it into code.

If instead we write the algorithm in code,


we have invested a lot of time in determining the
details of an algorithm we may not choose to
implement?

The GOAL of writing pseudo code, then, is


to provide a high-level description of an algorithm which
facilitates analysis and eventual coding

but at the same time suppresses many of the details that


vanish with asymptotic
© Dr. Jyoti notation
Lakhani
Why use pseudo code at all?

It allows the designer to focus on the logic of the


algorithm without being distracted by details of language
syntax.

It describe the entire logic of the algorithm so that


implementation becomes a rote mechanical task of
translating line by line into source code.

© Dr. Jyoti Lakhani


Here are a few general guidelines for checking your pseudo code:
-Naomi Nishimura

1. Mimic good code and good English:


It is still important that variable names be mnemonic, comments be included
where useful, and English phrases be comprehensible (full sentences are usually
not necessary).

2. Ignore unnecessary details:

you shouldn’t obsess about syntax at all

3. Arrange the sequence of tasks and write the pseudo code accordingly

4. Aim of the algorithm:


Start with the statement of a pseudo code which establishes the main goal or the
aim.

Example:
This program will allow the user to check the number whether it's
even or odd. © Dr. Jyoti Lakhani
5. Proper Indentation:
The way the if-else, for, while loops are indented in a program, indent the
statements likewise, as it helps to comprehend the decision control and
execution mechanism. They also improve the readability to a great extent.

Example:
if "1“ print response "I am case 1“ if "2“ print response
"I am case 2"

Example:
if "1"
print response "I am case 1"
if "2"
print response "I am case 2".
© Dr. Jyoti Lakhani
5. Don’t be labor the obvious:
In many cases, the type of a variable is clear from context; it is often
unnecessary to make it explicit.

6. Take advantage of programming short-hands:


Using if-then-else or looping structures is more concise than writing out
the equivalent in English;
Using parameters in specifying procedures is concise, clear, and
accurate, and hence should not be omitted from pseudo code.

7. Use appropriate naming conventions


The human tendency follows the approach to follow what we see. If a
programmer goes through a pseudo code, his approach will be the
same as per it, so the naming must be simple and distinct.

© Dr. Jyoti Lakhani


8. Use appropriate Naming Convention:
such as Camel Case for methods, upper case for constants and lower case for
variables.

9. Elaborate everything which is going to happen in the actual code:


Don’t make the pseudo code abstract

10. Use standard programming structures


such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in programming

11. Check whether all the sections of a pseudo code is complete, finite and clear to
understand and comprehend

12. Don’t write the pseudo code in a complete programmatic manner:


It is necessary to be simple to understand even for a layman or client, hence
don’t incorporate too many technical terms.
© Dr. Jyoti Lakhani
Advantages of Pseudo code
1. Improves the readability of any approach. It’s one of the best
approaches to start implementation of an algorithm

2. Acts as a bridge between the program and the algorithm or


flowchart

3. Also works as a rough documentation, so the program of one


developer can be understood easily when a pseudo code is written
out. In industries, the approach of documentation is essential. And
that’s where a pseudo-code proves vital

4. The main goal of a pseudo code is to explain what exactly each line
of a program should do, hence making the code construction
phase easier for the programmer

© Dr. Jyoti Lakhani


No broad standard for pseudo code syntax exists, as a program in pseudocode is not
an executable program, however certain limited standards exist

Pseudo code resembles skeleton programs which can be compiled without errors.

Flowcharts,
drakon-charts and
Unified Modelling Language (UML) charts can be thought of as a graphical
alternative to pseudo code, but are more spacious on paper.

Languages such as HAGGIS bridge the gap between pseudo code and code written in
programming languages.

- Wiki

© Dr. Jyoti Lakhani


Some Conventions to write Pseudo Code

Type of
Symbol Example
operation
Assignment ← or := c ← 2πr, c := 2πr
Comparison =, ≠, <, >, ≤, ≥
Arithmetic +, −, ×, /, mod
Floor/ceiling ⌊, ⌋, ⌈, ⌉ a ← ⌊b⌋ + ⌈c⌉
Logical and, or
Sums, products ΣΠ h ← Σa∈A 1/a

- Wiki
© Dr. Jyoti Lakhani
Action Words

Common Action Keywords:

Input: READ
OBTAIN
GET
Output:
PRINT
DISPLAY
SHOW
Compute:
COMPUTE
CALCULATE
DETERMINE
Initialize:
SET
INIT
Add one:
INCREMENT
BUMP
© Dr. Jyoti Lakhani
IF-THEN-ELSE
The general form is:
IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF

Example:

IF HoursWorked > NormalMax THEN


Display overtime message
ELSE
Display regular time message
ENDIF

© Dr. Jyoti Lakhani


WHILE

The general form is:

WHILE condition
sequence
ENDWHILE

The loop is entered only if the condition is true.

WHILE Population < LimitCompute


Population as Population + Births – Deaths
ENDWHILE

© Dr. Jyoti Lakhani


CASE
The general form is:

CASE expression OF CASE grade OF


condition 1 : A :
sequence 1 points = 4
condition 2 : B :
sequence 2 points = 3
... C :
condition n : points = 2
sequence n D :
OTHERS: points = 1
default sequence OTHERS :
ENDCASE points = 5
ENDCASE

© Dr. Jyoti Lakhani


FOR
The general form is:

FOR iteration bounds


sequence
ENDFOR

Example:

FOR each month of the year (good)


FOR month = 1 to 12 (ok)

FOR each employee in the list (good)


FOR empno = 1 to listsize (ok)

© Dr. Jyoti Lakhani


REPEAT-UNTIL
The general form is:

REPEAT
sequence
UNTIL condition

NESTED CONSTRUCTS
Example:
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF
UNTIL Temperature < zero
© Dr. Jyoti Lakhani
INVOKING SUBPROCEDURES
Use the CALL keyword.
For example:

CALL AvgAge with StudentAges


CALL Swap (CurrentItem, TargetItem)

CALL getBalance RETURNING aBalance

EXCEPTION HANDLING

BEGIN
statements
EXCEPTION
WHEN exception type
statements to handle exception
WHEN another exception type
statements to handle exception
END

© Dr. Jyoti Lakhani


© Dr. Jyoti Lakhani
10 Pseudocode and flowcharts
In this chapter you will learn about:
• the pseudocode for assignment, using ←
• the pseudocode for conditional statements
IF … THEN … ELSE … ENDIF
CASE … OF … OTHERWISE … ENDCASE
• the pseudocode for loop structures
FOR … TO … NEXT
REPEAT … UNTIL
WHILE … DO … ENDWHILE
• the pseudocode for input and output statements
INPUT and OUTPUT
(e.g. READ and PRINT)
• the pseudocode for standard actions
totalling (e.g. Sum ← Sum + Number)
counting (e.g. Count ← Count + 1)
• the standard flowchart symbols for the above statements, commands and
structures.

10.1 Introduction
Using pseudocode is a clear and concise way to represent an algorithm. Data items to
be processed by the algorithm are given meaningful names in the same way that
variables and constants are in a high-level programming language. Pseudocode is not
bound by the strict syntax rules of a programming language. It does what its name
says; it pretends to be programming code!
To ensure that pseudocode is easily understandable by others it is useful to be
consistent in the way that it is written. The pseudocode in this book is written in the
following way to help you understand the algorithms more easily:
• Courier New font is used throughout
• all keywords (words used to describe a specific action (e.g. INPUT) are written in
capital letters
• all names given to data items and sub-routines start with a capital letter
• where conditional and loop statements are used, repeated or selected statements
are indented by two spaces.

10.2 Assignment
Values are assigned to an item/variable using the ← operator. The variable on the
left of the ← is assigned the value of the expression on the right. The expression on
202
the right can be a single value or several values combined with mathematical
operators.

Table 10.1 Mathematical operators


Operator Action
+ add
– subtract
* multiply
/ divide
^ raise to the power
() group

Examples of pseudocode assignments:


Cost ← 10 Cost has the value 10
Price ← Cost * 2 Price has the value 20
Tax ← Price * 0.12 Tax has the value 2.4
SellingPrice ← Price + Tax SellingPrice has the value 22.4
Gender ←"M" Gender has the value M
Chosen ← False Chosen has the value False

Activity 10.1
What values will the following variables have after the assignments have
been completed?

Amount ← 100
TotalPrice ← Amount * 3.5
Discount ← 0.2
FinalPrice ← TotalPrice – TotalPrice * Discount
Name ←"Nikki"
Message ←"Hello" + Name

10.3 Conditional statements


When different actions are performed by an algorithm according to the values of the
variables, conditional statements can be used to decide which action should be taken.
There are two types of conditional statement as shown below with an example of

203
each.
• A condition that can be true or false: IF … THEN … ELSE … ENDIF, for example

IF Age < 18
THEN PRINT "Child"
ELSE PRINT "Adult"
ENDIF

• A choice between several different values: CASE … OF … OTHERWISE …


ENDCASE, for example

CASE Grade OF
"A" : PRINT "Excellent"
"B" : PRINT "Good"
"C" : PRINT "Average"
OTHERWISE PRINT "Improvement is needed"
ENDCASE

10.3.1 IF … THEN … ELSE … ENDIF


For an IF condition the THEN path is followed if the condition is true and the ELSE
path is followed if the condition is false. There may or may not be an ELSE path. The
end of the statement is shown by ENDIF.
A condition can be set up in different ways:
• Using a Boolean variable that can have the value TRUE or FALSE (see Section
11.4 for details of Boolean variables). For example

IF Found
THEN PRINT "Your search was successful"
ELSE PRINT "Your search was unsuccessful"
ENDIF

• Using comparison operators, as shown in Table 10.2. Comparisons are made from
left to right, for example A > B means is A greater than B. Comparisons can be
simple or more complicated. For example

IF ((Height > 1) OR (Weight > 20) OR (Age > 5)) AND (Age < 70)
THEN PRINT "You can ride"
ELSE PRINT "Too small, too young or too old"
ENDIF

204
Table 10.2 Comparison operators
Operator Comparison
> greater than
< less than
= equal
>= greater than or equal
<= less than or equal
<> not equal
() group
AND both
OR either
NOT not

The algorithm below checks if a percentage mark is valid and a pass or a fail. This
makes use of two IF statements. The second IF statement is part of the ELSE path of
the first IF statement. This is called a nested IF.

Figure 10.1

Activity 10.2
Change the algorithm to check for a mark between 0 and 20 and a pass
mark of 10. Decide what normal, boundary and erroneous data you will

205
need to fully test your algorithm.

10.3.2 CASE … OF … OTHERWISE … ENDCASE


For a CASE condition the value of the variable decides the path to be taken. Several
values are usually specified. OTHERWISE is the path taken for all other values. The
end of the statement is shown by ENDCASE.
The algorithm below specifies what happens if the value of Choice is 1, 2, 3 or 4.

CASE Choice OF
1 : Answer ← Num1 + Num2
2 : Answer ← Num1 - Num2
3 : Answer ← Num1 * Num2
4 : Answer ← Num1 / Num2
OTHERWISE PRINT "Please enter a valid choice"
ENDCASE

Activity 10.3
Use a CASE statement to display the day of the week if the variable DAY has
the value 1 to 7 and an error otherwise.

10.4 Loop structures


When some actions performed as part of an algorithm need repeating, this is called
‘iteration’. Loop structures are used to perform the iteration.
There are three different types of loop structure:

Operator Comparison
A set number of repetitions FOR … TO …
NEXT
A repetition, where the number of repeats is not known, REPEAT … UNTIL
that is completed at least once
A repetition, where the number of repeats is not known, WHILE … DO …
ENDWHILE
that may never be completed
Table 10.3

All types of loops can perform the same task, for example printing 10 stars.

FOR Counter ← 1 TO 10

206
PRINT "*"
NEXT
Counter ← 0
REPEAT
PRINT "*"
Counter ← Counter + 1
UNTIL Counter > 10
Counter ← 0
WHILE Counter < 10 DO
PRINT "*"
Counter ← Counter + 1
ENDWHILE

The FOR … TO … NEXT loop is the most efficient for this type of task.

10.4.1 FOR … TO … NEXT


A variable is set up with a start value and an end value and then incremented in steps
of one until the end value is reached and the iteration finishes. The variable can be
used within the loop so long as its value is not changed. This type of loop is very
useful for reading values into lists.

Figure 10.2

10.4.2 REPEAT … UNTIL


This loop structure is used when the number of repetitions/iterations is not known
and the actions are repeated UNTIL a given condition becomes true. The actions in
this loop are always completed at least once.

207
Figure 10.3

10.4.3 WHILE … DO … ENDWHILE


This loop structure is used when the number of repetitions/iterations is not known
and the actions are only repeated WHILE a given condition is true. If the WHILE
condition is untrue when the loop is first entered then the actions in the loop are
never performed.

Figure 10.4

Activity 10.4
a Write pseudocode to input 10 positive numbers and find the total and the
average.
b Write pseudocode to input positive numbers, –1 to finish, and find the
208
total and the average.
c Explain why you chose the loop structures for each task.

10.5 Input and output statements


INPUT and OUTPUT are used for the entry of data and display of information.
Sometimes READ can be used instead of INPUT; this is usually used for reading from
files, which is not covered in this textbook. Frequently PRINT is used instead of
OUTPUT.
INPUT is used for data entry. It is usually followed by a variable where the data
input is stored, for example:

INPUT Name
INPUT StudentMark

OUPUT/PRINT is used to display information either on a screen or printed on paper. It


is usually followed by a single value that is a string or a variable or a list of values
separated by commas, for example:

PRINT Name
PRINT "Your name is", Name
OUTPUT Name1, Name2, Name3

10.6 Standard actions


The ability to repeat actions is very important in the design of algorithms. When an
algorithm is turned into a program the same set of actions may be repeated many
thousands of times, for example, keeping a running total of the value of goods sold in
a supermarket.

RunningTotal ← RunningTotal + Value

Keeping a count of the number of times an action is performed is another standard


action, for example:

Count ← Count + 1

Counting is also used to count down until a certain value is reached, for example the
number of items in stock in a supermarket:

NumberInStock ← NumberInStock - 1

10.7 Examples of algorithms in pseudocode


209
Example 1
Tickets are sold for a concert at $20 each. If 10 tickets are bought then the discount is
10%; if 20 tickets are bought the discount is 20%. No more than 25 tickets can be
bought in a single transaction.
a Use pseudocode to write an algorithm to calculate the cost of buying a given
number of tickets.
b Explain how you would test your algorithm.
a

REPEAT
PRINT "How many tickets would you like to buy?"
INPUT NumberOfTickets
UNTIL NumberOfTickets > 0 AND NumberOfTickets < 26
IF NumberOfTickets < 10
THEN Discount ← 0
ELSE
IF NumberOfTickets < 20
THEN Discount ← 0.1
ELSE Discount ← 0.2
ENDIF
ENDIF
Cost ← NumberOfTickets * 20 * (1 – Discount)
PRINT "Your tickets cost", Cost
b Would use test data with values of
0, 26 Expected result rejected
1, 25 Expected results 20, 400
9, 10 Expected results 180, 180
19, 20 Expected results 342, 320

Activity 10.5
For the test data given in Example 1, identify the type of test data used and
suggest some more test data.

Example 2
A school with 600 students wants to produce some information from the results of the
four standard tests in Maths, Science, English and IT. Each test is out of 100 marks.
210
The information output should be the highest, lowest and average mark for each test
and the highest, lowest and average mark overall. All the marks need to be input.
a Use pseudocode to write an algorithm to complete this task.
b Explain how you would test your algorithm.
a

OverallHighest ← 0
OverallLowest ← 100
OverallTotal ← 0
FOR Test ← 1 TO 4
SubjectHighest ← 0
SubjectLowest ← 100
SubjectTotal ← 0
CASE Test OF
1 : SubjectName ←"Maths"
2 : SubjectName ←"Science"
3 : SubjectName ←"English"
4 : SubjectName ←"IT"
OTHERWISE
ENDCASE
FOR StudentNumber ← 1 TO 600
REPEAT
PRINT "Enter Student", StudentNumber,""s mark for",
SubjectName
INPUT Mark
UNTIL Mark < 101 AND Mark > -1
IF Mark < OverallLowest THEN OverallLowest ← Mark
IF Mark < SubjectLowest THEN SubjectLowest ← Mark
IF Mark > OverallHighest THEN OverallHighest ← Mark
IF Mark > SubjectHighest THEN SubjectHighest ← Mark
OverallTotal ← OverallTotal + Mark
SubjectTotal ← SubjectTotal + Mark
NEXT
SubjectAverage ← SubjectTotal/600
PRINT SubjectName
PRINT "Average is", SubjectAverage

211
PRINT "Highest Mark is", SubjectHighest
PRINT "Lowest Mark is", SubjectLowest
NEXT
OverallAverage ← OverallTotal/2400
PRINT "Overall Average is", OverallAverage
PRINT "Overall Highest Mark is", OverallHighest
PRINT "Overall Lowest Mark is", OverallLowest
b For the algorithm to be tested by dry running, it would be a good idea to reduce the
number of students to 5 and the number of subjects to 2.

Activity 10.6
a Identify the changes you would need to make to the algorithm for
Example 2 to reduce the number of students to 5 and the number of
subjects to 2.
b Identify the test data needed to test Example 2 with the reduced number
of students and subjects.
c With the set of data you have chosen, set up and complete a trace table
so that you can compare your expected results with the actual results
when you dry run the algorithm.

10.8 Standard flowchart symbols


Flowcharts are drawn using standard symbols.

10.8.1 Begin/End
Terminator symbols are used at the beginning and end of each flowchart.

Figure 10.5 Terminator symbols

10.8.2 Process
Process symbols are used to show when values are assigned to an item/variable like
212
an assignment in pseudocode.

Figure 10.6 Process symbol

10.8.3 Input/Output
Input/Output symbols are used show input of data and output of information.

Figure 10.7 Input/Output symbol

10.8.4 Decision
Decision symbols are used to decide which action is to be taken next. These can be
used for selection and repetition/iteration.

Figure 10.8 Decision symbol

10.8.5 Flow lines


Flow lines are used to show the direction of flow which is usually, but not always,
top to bottom and left to right.

Figure 10.9 Flow line

Example 1 (continued)
213
Tickets are sold for a concert at $20 each, if 10 tickets are bought then the discount is
10%, if 20 tickets are bought the discount is 20%. No more than 25 tickets can be
bought in a single transaction.
c Draw a flowchart for the algorithm to calculate the cost of buying a given number
of tickets.

Figure 10.10 Flowchart for Example 1

214
Activity 10.7
Draw a flowchart for the algorithm given in Example 2.
Choose the method you think is the clearest way to show this algorithm and
explain why it is the clearest.

215
End-of-chapter questions
1 Show two ways of selecting different actions using pseudocode.
2 You have been asked to write the pseudocode to choose the correct routine from
the menu shown below.
a Decide which type of conditional statement you are going to use.
b Explain your choice.
c Write the pseudocode.
d Select your test data and explain why you chose each value.

Figure 10.11

3 Show three ways a loop to add up five numbers and print out the total can be set
up using pseudocode. Explain which loop is the most efficient to use.
4 A sweet shop sells 500 different sorts of sweets. Each sort of sweet is identified by
a unique four-digit code. All sweets that start with a one (1) are chocolates, all
sweets that start with a two (2) are toffees, all sweets that start with a three (3) are
jellies and all other sweets are miscellaneous and can start with any other digit
except zero.
a Write an algorithm, using a flowchart, which inputs the four-digit code for all
500 items and outputs the number of chocolates, toffees and jellies.
b Explain how you would test your flowchart.
c Decide the test data to use and complete a trace table showing a dry run of your
flowchart.
5 The temperature in an apartment must be kept between 18°C and 20°C. If the
temperature reaches 22°C then the fan is switched on; if the temperature reaches
16°C then the heater is switched on, otherwise the fan and the heaters are switched
off.
The following library routines are available:
• GetTemperature

216
• FanOn
• FanOff
• HeaterOn
• HeaterOff
Write an algorithm, using pseudocode or a flowchart, to keep the temperature at
the right level.
6 Daniel lives in Italy and travels to Mexico, India and New Zealand. The time
differences are:

Table 10.4
Country Hours Minutes
Mexico –7 0
India +4 +30
New Zealand +11 0

Thus, if it is 10:15 in Italy it will be 14:45 in India.


a Write an algorithm, using pseudocode or otherwise, which:
• inputs the name of the country
• inputs the time in Italy in hours (H) and minutes (M)
• calculates the time in the country input using the data from the table
• outputs the country and the time in hours and minutes.
[4]
b Describe, with examples, two sets of test data you would use to test your
algorithm.
[2]
Cambridge IGCSE Computer Studies 7010/0420 Paper 11 Q17 June 2011
7 A school is doing a check on the heights and weights of all its students. The school
has 1000 students.
Write an algorithm, using pseudocode or a flowchart, which
• inputs the height and weight of all 1000 students
• outputs the average (mean) height and weight
• includes any necessary error traps for the input of height and weight.
[5]
Cambridge IGCSE Computer Studies 7010/0420 Paper 11 Q17 November 2010
8 A small café sells five types of item:
• bun 0.50 dollars
• coffee 1.20 dollars
• cake 1.50 dollars
217
• sandwich 2.10 dollars
• dessert 4.00 dollars
Write an algorithm, using pseudocode or a program flowchart only, which
• inputs every item sold during the day
• uses an item called ‘end’ to finish the day’s input
• adds up the daily amount taken for each type of item
• outputs the total takings (for all items added together) at the end of the day
• outputs the type of item that had the highest takings at the end of the day.
[6]
Cambridge IGCSE Computer Studies 7010/0420 Paper 13 Q16 November 2012
9 5000 numbers are being input which should have either one digit (e.g. 5), two
digits (e.g. 36), three digits (e.g. 149) or four digits (e.g. 8567).
Write an algorithm, using pseudocode or a flowchart only, which
• inputs 5000 numbers
• outputs how many numbers had one digit, two digits, three digits and four digits
• outputs the percentage of numbers which were outside the range.
[6]
Cambridge IGCSE Computer Studies 7010/0420 Paper 13 Q15 November 2013

218
ALGORITHMS AND
FLOWCHARTS
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
FLOWCHART SYMBOLS
Basic
Name Symbol Use in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program


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


Lft

• Step 2: Lcm  Lft x 30


Lcm  Lft x 30
• Step 3: Print Lcm
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

• Step 2: AL x W
W, L

• Step 3: Print A ALxW

Print
A

STOP
EXAMPLE 4

• Write an algorithm and draw a flowchart that will


calculate the roots of a quadratic equation
ax 2  bx  c  0
b 2  4ac
• Hint: d = sqrt ( ), and the roots are: x1 =
(–b + d)/2a and x2 = (–b – d)/2a
EXAMPLE 4

Pseudocode:
• Input the coefficients (a, b, c) of the quadratic equation
• Calculate d
• Calculate x1
• Calculate x2
• Print x1 and x2
EXAMPLE 4
START

• Algorithm:
Input
• Step 1: Input a, b, c a, b, c
b b  4 a  c
• Step 2: d  sqrt ( ) d  sqrt(b x b – 4 x a x c)

• Step 3: x1  (–b + d) / (2 x a) x1 (–b + d) / (2 x a)

• Step 4: x2  (–b – d) / (2 x a)
X2  (–b – d) / (2 x a)
• Step 5: Print x1, x2
Print
x1 ,x2

STOP
DECISION STRUCTURES

The expression A>B is a logical expression •


it describes a condition we want to test •
if A>B is true (if A is greater than B) we take the •
action on left
print the value of A •
if A>B is false (if A is not greater than B) we take the •
action on right
print the value of B •
DECISION STRUCTURES

Y N
is
A>B

Print A Print B
IF–THEN–ELSE STRUCTURE

• The structure is as follows


If condition then
true alternative
else
false alternative
endif
IF–THEN–ELSE STRUCTURE

• The algorithm for the flowchart is as follows:


If A>B then
print A
Y N
is
else A>B
print B
endif Print A Print B
RELATIONAL OPERATORS

Relational Operators
Operator Description
> Greater than
< Less than
= Equal to
 Greater than or equal to
 Less than or equal to
 Not equal to
EXAMPLE 5

• Write an algorithm that reads two values, determines the


largest value and prints the largest value with an identifying
message.
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX  VALUE1
else
MAX  VALUE2
endif
Step 3: Print “The largest value is”, MAX
EXAMPLE 5
START

Input
VALUE1,VALUE2

Y is
N
VALUE1>VALUE2

MAX  VALUE1 MAX  VALUE2

Print
“The largest value is”, MAX

STOP
NESTED IFS

• One of the alternatives within an IF–THEN–ELSE statement


• may involve further IF–THEN–ELSE statement
EXAMPLE 6

• Write an algorithm that reads three numbers and prints


the value of the largest number.
EXAMPLE 6
Step 1: Input N1, N2, N3
Step 2: if (N1>N2) then
if (N1>N3) then
MAX  N1 [N1>N2, N1>N3]
else
MAX  N3 [N3>N1>N2]
endif
else
if (N2>N3) then
MAX  N2 [N2>N1, N2>N3]
else
MAX  N3 [N3>N2>N1]
endif
endif
Step 3: Print “The largest number is”, MAX
EXAMPLE 6

• Flowchart: Draw the flowchart of the above Algorithm.


EXAMPLE 7
• Write and algorithm and draw a flowchart to
a) read an employee name (NAME), overtime hours worked
(OVERTIME), hours absent (ABSENT) and
b) determine the bonus payment (PAYMENT).

You might also like