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

Computer Science

Rudlimentsof Algorithm and Flowchart

13Algonthns
solvea particular problem using a
Similariy,
to. computer program we steps,toTofollow
the codein a particular Computer language to implement the have a specific
design set ofof arules
the logic and
program
severaltoos may be used, like the development of an algorithmfrom the problem definition.
Algorithmis a sequence of precise and unambiguQus instructlons designed in such a way that if
An | inthe specified sequencethe
exrecuted desired result is obtained within a finite number of steps. Definition of
theyare need to be
the steps that followedto achieve the desired result form the algorithm. It should be: Algorithm
short
,Effective,
In which means that an answer should be found when the algorithm is applied, and it
Finishes,thatis. it has a finite number of steps and should not go on infinitely

Asanexampletake the problem of finding the average of 'n' numbers. The program can be writen for a
&fixed numbers or the program can be designed for a variable number of inputs. We (An Algorithw is a
of known algorithm for both the cases. sequence of
belowthe
discuss precise and
for findingthe average of fixed number of inputs are:
a
Thesteps
unambiguous
thenumbers (n, + n2 + n3 +,.. + n,) to get the sum S instructions to
Step1: Add
sum by the number count i.e. nto get the average Avg := S/n obtain the
Step2: Divide the Solution to a
Avg
Step3: Print the average problem in a
algorithm, the Symbol := indicates an assignment or store operation i.e. the value S/n is stored in
In anvariable
finite number of
Avg. In contrast, the = symbol is used to compare two values, as shown later. steps.)
octens for finding the average for variable number of inputs are:
variable called Sum to zero i.e. Sum :=0
Stepl: Initialise a
i.e. C:=0
Step2: Initialise a coOunter C to 0 to count the number of inputs,
scnts
Step3: Ask for the input I n p n Inp
Shen4: Add the input value to the existing value of the variable Sum i.e. Sum := Sum +
Step5: Increase the count value by 1 i.e. C;=C+1
Step6: If more numbers are to be input, then go to Step3, else go to Step7
Step7: Calculate the average Avg as the Sum divided by the countC i.e. Avg := Sum/C
Step8: Print the average Avg and terminate program
In the first case the program design is specific and each time the numbers are changed, the program also
needs to be changed to accommodate the new numbers. In the second case the program is a general one
and the user is able to input any number of inputs to find the average.
states the steps that
It can be seen that the second algorithm is a little complicated than the first but it clearly and hence is a
carry out the average
need to be taken in case we want to prepare a general program to
same problem can
DEtter choice. Thus the have different algorithms and different procedures.
JExample-1: Algorithm to add two numbers:
Step1. Input a Examples of
Algorithms
Step3. sum := a+h
Step4. Print sum
Step5. Stop
ample-2: Algorithm to derive the absolute value of any number.
Dumhe absolute value of a number (i.e. the positive magnitude of a value) we have to first check if the
number itself.
IFthpositve or negative, If the number is positive the absolute value is the same as the
er is negative then the absolute value is the negative of the given number.
Step1. Input num
Step2.. If num < 0, then
num := (-1) * num
Step3. Print num
Step4. Stop
213 P1-7-3
Part 1: Chapter 7

1Example-3: Algorithm to check if a number is even or odd:


Anumber is even if it is evenly divisible by 2 and hence produces a 0 remainder, else it is odd. In that
remainder of dividing a
remainder of 1 is obtained. Modulo operation is used to get the
another number Y. Thus 14 (modulo) 3 is 2, as the remainder of the division is 2. number Xby
Step1: Input num
Step2: If num (modulo) 2 <>0, then [the symbol <> is used to denote 'not equal to
a. Print "Odd Number"
Step3: Else
Print "Even Number"
Step4: Stop
Example-4: Algorithm to find the percentage of marks obtained in Physics, Maths, and Computer Slenra.
a student, out of a total of 300 marks.
Step1. sum : 0 (varlable sum assigned value O)
Step2. Input Phy (input marks of physics)
Step3. sum : sum + Phy (Add marks of physics to sum)
Step4. Input Math (input marks of math)
Step5. Sum :=sum + Math (Add marks of math to sum)
Step6. Input Coms (input marks of computer science)
Step7. Sum := Sum+ Coms (Add marks of computer science to sum)
Step8. Percentage ;= sum*100/300
Step9. Print Percentage
Step10. Stop
Example-5: The same problem can also be done for a variable number of subjects, using a counter:
Step1. sum :=0 (Declare variable for sum calculation and initialise it to O)
Step2. Count :=0 (Declare variable for counting number of subjects and initialise it to )
Step3. Input number of subjects: num(Input the total number of subjects to use)
Step4. Input marks of a subject: marks (Input marks for a given subjec)
Step5. sum :=Sum + marks (Add marks to sum total)
Step6. count := COunt + 1 (Increase count value by 1)
Step7. If count <> num then (If count value is not equal to num then loop)
Go to Step4
Step8. percentage := [sum/(num*100)] *100
Step9. Print percentage
Step10. Stopo
The above algorithm shows the use of a 'loop", i.e. a section of the code that gets repeated (steps 4to 7).
Example-6: Ashopping mall is giving discount on items purchased. If the purchased item is a shirt, then
10% disCount is given. the item is atrouser, then discount given is 20%. If item is a cap then 5% discount
is given. Write down the algorithm for the net purchase amount.
Step1: Input item type: Item
Step2: Input item price: Price
Step3: If Item = "shirt" then
a. Amount := Price- Price * 10 /100
Step4: If Item = "trouser" then
2
a. Amount := Price - Price * 20 / 100
Step5: If Item = "cap" then
a. Amount = Price - Price * 5/100
Step6: Print Amount
Step7: Stop
Note the use of the'operator to compare the value stored in item with other values.

P1-7-4 214
Rudiments of Computer Science Algorithm and Flowchart

erample-7: Let us now write down the algorithm to generate the series 1, 2,3, 4,5, 6..
The series is generated by adding 1to the previous term in the series, starting from 1.
Step1. count := 1 (Declare counter and inltlallse it to )
Step2. Input the total number of terms to print:N
Step3. Loop while count <= N (Continue loop as long as count<=)
Print count
b count := count+ 1 ofst (/ncrement count value by )
Step4. Stopuno o a a
nnerate the series we have used a different form of the loop statement. Note that the steps 3a and
3b get repeated as long as Count value less than or equal to N. This is expressed by using the 'Loop
while' statement. The steps 3a and 3b loop as long as the condition count<=N is true. The moment the
ondition becomes false, the loop ends and stops repeating the statements 3a and 3b.
Esample-8: Algorithm to generate the series 1', 2², 33, 4, 5², 6 and get.its sum up to Nterms.
The problem is similar to the previous one, however instead of the count value, the square of the count
value is getting added here.
Step1: count := 1 (Decdare COunter and initialise it to 1)
Step2: sum := 0
Step3: Input the total number of terms to add: N
Step4: Loop while count <= N (Continue loop as long as count<=M
sum := Sum + count*count
b. COunt:= Count + 1 (Increment count value by 1)
Step5: Print sum
Step6: Stop
Example-9: Let us now write down the algorithm to print the first Nodd numbers i.e. 1, 3, 5, 7, 9. When an
Step1: count := 1 (Decdare variable for cOunting nunmber of terms and initialise it to ) soso ni algorithm
Step2: Term := 1 (Declare variable for series term and initialise it to first term value ie. 1) expressed in a
Step3: Input the total number of terms to print:N pictorial manner
Step4: Loop while count <=N (Continue loopas long as count<-Mon te 0 a e c with special
a. Print Term symbols to
indicate the
b. Term :=Term + 2 (Add 2 tocurrent value of term to get the next term value) different types of
C. count :=count+1 instructions, then
Step5: Stop it is called a
Flowchart.
74 Flowcharts
When an algorithm is expressed in apictorial manner with special symbols to indicate the different
types of instructions, then it is called a flowchart. The actual instructions are written inside boxes of Definition of
diferent shapes indicating different functions. Solid lines with arrows indicating the flow of programs are then Flowchart
used to connect the boxes. The different symbols which are used foraflowchart include:
Terminal The Ferminal denotes the START, STOP or HALT in the program logic flow. It is the first
arnd the last symbol in a program. Halt can be used when there is an eror condition in the
program.

Input Ary ifput or output operation from an input/output device is shown by this symbol.
Output Ahe input can be from the keyboard, disk, tape, mouse etc. while output can be to the Shapes used
monitor, printer etc. with a
mis symbol is used to represent arithmetic and data movement operations. All Flowchart
Processing arithmetic processes (add, subtract, multiply, divide etc.) and logical process of moving
the data from one location to another are denoted by this symbol.

215 P1-7-5
Part 1:Chapter 7
decision is to be made and a
This symbol is used at a point where a
Declsion necessary depending upon the decision. The criteria
inside the box and the number of paths to follow should also be
mentioned. branchiIndincagtea
for the decision should be

function in a flowchart,
Function This symbol is used to indicate any predefined The funcion
flowchart or an algorithm or can be
name may be defined by a separate any
function. standard
This is the symbol of a Connector. Whenever a flowchart becomes too
difficult to fit within a given page, it can be broken down into parts and the \ong andis
joined by Connectors to maintain continuity. This symbol thus signifies an partS are
an exit from one part of the flowchart to another. enty to ox
Flow-lines with arrowheads are used to indicate the flow of data or an operatio .
determines the exact sequence in which the program flows.

AThe advantages in using a flowchart for planning a program are stated below:
Advantages of a. Since flowcharts are not based on a particular programming language, once a logical solution of
using Flowcharts problem has been charted it can be implemented in any programming language.
Being pictorial in nature, flowcharts are easy to understand.
C. Large programs can be broken down into smaller modules and different individuals entrusted wik
working out a particular module. Amain flowchart showing the interconnectivity of the different
modules will help to put together the final program.
d. Error or bug in a program can be easily detected from a graphical flowchart.
In spite of these apparent advantages in using flowcharts, there are some obvious disadvantages in Sign
flowcharts. Some of them are stated below:
Being pictorial in nature, flowcharts are time consuming to draw. When writing small programs t
may be easier to draw flowcharts but for large programs it may becomes very inconvenient.
Disadvantages
In case any change needs to be incorporated, it is not easy to do the same in an existing flowchart but
the flowchart needs to be redrawn and this is a time consuming process.
Fkample-10: Add two numbers. Example-11: Get the absolute value of any number.
Examples of (Use of branching operation with a decision box)
Flowcharts
Start Start

Input a, b Input N

Yes
Sum :=atb N0 N=(1N
No
Print Sum S,
Print N

Stop

P1-7-6 216
Rudiments of Computer Science Algorlthm and Flowchart
7
Example-12: Check if number is even or odd. Exarmple-13: Print the serles 1, 2,3, 4, 5, 6...
(Use of loop operation, using a decision box)

Start Start

Input N Input N(total terms)

Yes oount 1
(mod)2 Print"Even"

No
No
count
Print "Odd" <aN Stop
Yes

Print count
Stop

count:= count+1

Dámple-14: Check if profit or loss is made.


during buying/selling items.
Exafnple-15: Print the factors of a given number.

Start start

Input cost price CP Input N

Input selling price SP count:1

Yes No
SP-CP Print "Profit" count Stop
>0

No Yes

Yes
SP-CP Print"Loss Yes When an
<0 Nmod count Print count
0 algorithm is
No written in a
No structural form
Print "No gain no loss" that resembles

count:= count+1
computer
instructions it is
Stop called a
Pseudocode
7.5 Pseudocode
Toovercome the disadvantages of a flowchart the technique of pseudo code can be used. Pseudo means Pseudocode
imitation and code means the instructions for the program. The pseudo or false instructions are written in
acommon language in a structural form that resembles computer instructions.
Since a pseudo code is similar to a computer program in structure but written in a common ordinary language
IS Sometimes
algorithm
called Program Design Language (PDL). The pseudo code is thus astep in between the
and the actual program code.

217 P1-7-7
Part 1:Chapter 7
been found to be
The basic logic structures that are used to write a pseudo cOde and that have sufficient in
writing almost all computer programs are:
1. Sequential logic
2. Conditional logic
3. Iterative logic any
program is in a linear manner without START
Sequential logic: Implies the flow of stepwise. After carrying out an instruction the
branching, with instructions written down of code. There is no branching in between and
Sequential logic line
program control passes on to the nextmanner. The figure on the right shows the flowchart
the program proceeds in a sequential PROCESS1
for sequential logic.
product of the
inputs two numbers, finds out the
The following program pseudocode PROCESS 2
numbers and then prints the result.
Input tWO numbers a & b
Calculate result ab STOP
Print result
Stop
Conditionallogic: This logic structure is used to perform a set of START
instructions based on one or more conditions. Depending upon
taken and the
Conditional logic the condition one or more decisions can be
If-Then-Else
program logic branches to different paths. The cONDITION False
structure or If-Else structure is used to depict such a situation. If
a certain condition is satisfied then the program carries öut a set
of instructions else another set of instructions are carried out. True
The figure on the right shows the flowchart for conditional logic.
PROCESS 1 PROCESS2
The following example shows the pseudocode of a program that
inputs two numbers and determines which is the larger one. (The
line numbers are given to help in understanding the logic and may
not be used in an actual pseudocode). STOP
1 Input twO numbers: a, b
2 Ifa>b then
3 Print "a is greater than b"
Else
5 Ifb>a then
6 Print "b is greater than a"
7 Else
Print "a is equal to b"
End if
10 End if
11 Stop
Note the use of indentations to indicate a subsection of the
START
code. Line3 is a subsection which is under the f statement of Line2.
Hence Line3 is indented to the right with respect to Line2. Similarly,
Line5 is indented to the right with respect to Line4 as it is a
subsection of the else statement of Line4. In this manner, byusing CONDITION
False
indentations, each logical block is identified. ?

Iterative logic: When one or more instructions need to be True


executed several times based on certain conditions then we get STOP
Iterative logic iterative logic. The instruction block that needs to be repeated is put PROCESS 1
inside the body of the loop and the looping continues as long as a
certain condition is satisfied. The While, Repeat-Until, and For
Next structures are usually used to indicate a loop in a pseudocode. PROCESs 2
The general structure of an iterative loop is shown by the flowchart
on the right.

P1-7-8 218
Rudiments of Computer Science Algorithm and Flowchart

In the following example the pseudocode is used to calculate the factorial of an input number.
Input the number: num
Define: factorial41
Initialise loop counter: i+1
While i<= num, loop
factorial factorial *i

End loop
Print the value of factorial
Stop
The advantages of using a pseudocode are:
1. It is easier to convert a pseudocode to a programming language code than from a flowchart.
Advantages of
2. It is alot easier to modify a pseudocode than a flowchart, in case some change in logic or additional using
features needs to be incorporated. pseudocode
3. Since pseudocode generation does not involve any graphics, it is much less time consuming to write a
pseudocode than to draw a flowchart.
In soite of the above advantages there are certain disadvantages which include:
1. Graphic representation is much easier to interpret but pseudocode does not have any such scope. Disadvantages
2. Pseudocode generation does not involve any standard rules and hence different programmers
have their ownstyle of writing a pseudocode resulting in a lack of uniformity.
Example16: Let us now write down the pseudocode to reverse the digits of a number.
Define variables: num, rev_ num 0 Examples of
Input: num pseudocode
While num # 0
rev num4 rev_num*10+ num(MOD)10
num+ INT(num/10)
End loop
Print rey_num
Stop

Example17: Write the pseudocode to find the real and imaginary roots of a quadratic equation.
In dealing with this problem as we have discussed earlier, we have to take as input the coefficients of the
different terms of the quadratic equation of the form ax+bx+c=0. Then we have to check whether the
discriminant D=b' 4ac is equal tozero, positive or inegative. Based on the sign of D, the roots will be real or
imaginary. We have to check if a=0, in that case the equation will not be a quadratic one and will have to ask
for afresh input. The pseudocode for the above problem is:
Input the coefficients: a, b, c while a0
dbe-4*ac
Ifd= 0
roott --b/(2*a), root2 4 -b/(2'a)
Print root1, root2
Ifd>0
-b2al)an
root t--b/2*a)-(vay2a), root2
Print roott, root2
Ifd <0
dd
rooti e- -bI(2'a)+1(v4)I2*a), root2+-bI(2*a)-i(y2*a)
Print imaginary roots: roott, root2st
Stop
219 P1-7-9
Part 1: Chapter 7

Example18: Write down the pseudocode to read 10 real numbers and find their average.
Define an array to hold 10 real numbers: Arr(10)
Define variables: +1,sum - 0, average
While i< 10
Input Arr()
End loop
i+ 1
While i < 10
sum sum +Arr)

End loop
average- sum/10
Print average
Stop

Example19: Write the pseudocode to reverse the order of the numbers in an array of numbers.
Define variables: i1, temp, n
Define an array to hold n real numbers: Arrn)
Input the number offelements in the array: n
While i <n
Input Arr)
End loop
i-1
While i < nN2
temp - Arr(i)
Arr(i) +Arr(n-i+ 1)
Arr(n -i+1) + temp
End loop
i-1
While i<En
Print Arr()
End loop
Stop

Example20: Write the pseudocode to check whether a string is a palindrome or not.


Define variables:i+1, temp, len-0
Define two string variables: String1, String2
Input string to check: String1
String2 = String1
Repeat
If String1) <> End of String
len len+1:ie jt1
Until End of String
ie1
While i <= len
String2(len-i+1) + String1(0
End loop
fString2 = String1 then
Print "The string is a palindrome"
Else
Print "The string is not a palindrome"
Stop

P1-7-10 220
Science
Rudiments of Computer Algorithm and Flowchart

The Fact FIle


Ho Proaram Definition Phase is used to work out what must be done to solve the problem and is used
extract from the problem statement the different inputs, outputs, rules etc. that must be
incorporated in the program.
The Program Design Phase deals with the 'how' part of the programming.Since there can be more than one way to
solve a problem it may not be always easy to find the best solution to a particular problem.
The Program Coding Phase is the actual coding of the program i.e. it is the process of translating the
roaram logic into program code in astep by step manner using a particular programming language.
The Program Testing &Debugging Phase is used to check if the program runs correctiy ie. whether we get the
desired outputs. For a good program, even if invalid inputs are supplied the program should be able to detect them.
The Program Documentation Phase is required to make a program code properly understandable.
Comments should be inserted at strategic points to highlight the utility or use of aparticular section.
An Algorthm is a sequence of precise and unambiguous instructions designed in such away that if the instructions
are executed in the specified sequence the desired result is obtained within a finite number of steps.
Sometimes by increasing the amount of space used for storing the data, the time required for
processing the data may get reduced. On the other hand reducing the space for storing the data can
lead to an increase in the time required to process the data. This is known as Space-Time Trade-off.
When an algorithm is expressed in a pictorial manner with special symbols to indicate the different types of
instructions, then it is called a flowchart. The actual instructions are written inside boxes of different shapes
indicating different functions. Solid lines with arrows indicating the flow of programs are then used to connect the
boxes.
Pseudo means imitation and code means the instructions for the program. The pseudo or false
instructions are written in a common language in a structural form that resembles computer
instructions

Review.Questiorns
1 each
O1, Multiple Choice Questions. Select any one from the four options.
An algorithm:
a. May or may not produce the exact solution to a problem
b. Should get the result within a finite time limit
C. May take any amount of time tO process the data
M
d. May not follow a definite sequence of steps
When an algorithm is expressed in a pictorial manner with special symbols to indicate the different
types of instructions, then it is called a:
a. logic chart b. design chart C. flowchart d. algo chart
What type of an operation is denoted by the Terminal symbol in a flowchart?
a. START b. STOP C. HALT d. All of these
flowchart?
i) What type of an operation is denoted by the Parallelogram symbol in a
a. calculation b. input or output C. decision d. process
flowchart?
What type of an operation is denoted by the Rectangle symbol in a
b. terminal C. process d. decision
a. input or output
in aflowchart?
vi) What type of an operation is denoted by the Rhombus symbol
a. terminal b. decision C. input or output d. process
1each
Q2. Short Answer type questions:
What is an algorithm?
Write the algorithm to increment a variable num by 1.
What is a flowchart?
) Draw the flow chart to decrease the value of a variable num by 1.
V) State one advantage of using a flowchart.
State one disadvantage of using aflowchart
vii) What is the use of the Parallelogram symbol in a flowchart?
vi) What is the use of the Rectanale symbol in a flowchart?

221 P1-7-11
Part 1: Chapter 7

ix) What is the use of the Rhombus symbol in a flowchart?


X) What do you mean by a pseudocode?
xÌ) State one difference between a pseudocode and an algorithm.
xi) State one advantage of using pseudocode.
xii) State one disadvantage of using pseudocode.
x0v) Write the pseudocode to increment a variable y by 1?
xv) Name any one of the basic logic structures that is used to write a pseudo code.
Q3. Long Answer type questions: 7each
A Write the algorithm to Input the length and breadth of arectangle and calculate and disolaw .
area and perimeter. Explain any two phases of program development.
3+2+2
Write the algorithm to input the number of terms for the following series and print the terms of the
series up to that number:
1, 5, 25, 125,
State any two advantages of using a flowchart. 2
i) Write the algorithm to input three numbers and print the larger of the three numbers.
Explain the terms 'sequential logic' and 'iterative logic'.
iv) Draw the flowchart to input two numbers x and y and print the result x without using ary
power
or exponent operator [hint: use iterative logic].
5
Explain the terms 'conditional logic' and 'pseudocode'.
2
v) What is aflowchart? Draw the flowchart to find the sum of the numbers which are
aset ofN numbers input by the user. divisible by 7in
2+5

P1-7-12 222

You might also like