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

Class Notes

On
ALGORITHMS
And
FLOWCHARTS
Class Notes on ALGORITHMS and FLOWCHARTS

ALGORITHMS

Definition:
The finite sequence of steps that a process performs in order to solve a problem is known as an
algorithm. Algorithms are used for calculation, data processing, and several other activities in the
fields of mathematics, computer science and other related subjects.

Properties of algorithms:
1. An algorithm is a step by step procedure.
2. The number of steps in an algorithm is finite.
3. An algorithm is result oriented, i.e. it has a purpose and gives certain results.
4. The execution of an algorithm stops after in a definite time.
5. Each step is unambiguous, i.e. each step has a well defined meaning.
6. An algorithm can accept inputs and give outputs.

Advantages of using algorithms:


1. Efficiency: Algorithms aid in solving problems with an aim to reduce time and space
requirements for the solution. Each algorithm is associated with a time and cost factor.
2. Abstraction: Algorithms provide a level of abstraction in solving problems. A large
complex problem can be sub-divided into smaller simpler ones. The simpler problems are
abstractions of the more complicated one.
3. Reusability: Algorithms are often reusable in many different situations.

Expressing algorithms:
Algorithms can be expressed in the following ways:
1. Natural Language
2. Flowcharts
3. Pseudocode
4. Programming languages

Example :
Algorithm to find sum and average of two numbers —

Input : Two numbers


Output: Sum and Average
Step - 1. INPUT two numbers, x and y
Step - 2. COMPUTE, sum := x + y
Step - 3. COMPUTE, average := sum / 2
Step - 4. PRINT sum, average
Step - 5. END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |2
Class Notes on ALGORITHMS and FLOWCHARTS

FLOWCHARTS

Definition:
A flowchart is a graphical representation of an algorithm. Each step in the process is represented by
a defined symbol and contains a short description of the process step. The symbols are linked
together with arrows that show the direction of the process flow. Since flowcharts have a pictorial
format, they are often easier to understand than the textual formats.

Symbols used in flowcharts:

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching

Connector or joining of two parts of program

Arrows for depicting flow of control

Example:
Flowchart to find sum and average of two numbers.

START

INPUT x, y

sum = x + y

average = sum / 2

PRINT Average

END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |3
Class Notes on ALGORITHMS and FLOWCHARTS

DATA ITEMS

There are two basic types of data items:


a) Constants
Data items that retain their values throughout the program are termed as constants. A constant
is a specific value or character string used explicitly in an operation.
For example:
 25 in the statement: ADD 25 TO x
 “Hello!” in the statement: PRINT “Hello”
 3.141593 in the statement: ASSIGN pi := 3.41593
b) Variables
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. The value may
change several times during the execution of a program.
For example:
 x in the statement: ADD 25 TO x
 name in the statement: ASSIGN name := “Tom”
 myvar in the statement: PRINT myvar

DATA TYPES

Data types determine the type of values that variables and constants may have. The common data
types supported in most programming languages are:

a) Integer
Integers are numeric data items, which are either positive or negative including zero. For
example 1, 48888, -56, 0, 456 etc. Some programming languages put restrictions on the
magnitude of integers which may be used in program instructions.

b) 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.
For example: 1.5, 458.4589, -0.569 etc
Floating Point
Floating point data items are numbers, which are, held as binary fractions by a computer. The
numbers have a mantissa and an exponent.

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |4
Class Notes on ALGORITHMS and FLOWCHARTS

For example:
Number Mantissa Exponent
62.5 = 0.625 × 102 0.625 2
62500 = 0.625 × 105 0.625 5
0.0000625 = 0.625 × 10-4 0.625 -4

c) Character and String


Character data can store a single character. They are typically enclosed within single quotes.
For example: ‘a’, ‘C’, ‘8’, ‘$’.
Strings are groups of characters treated as a single element. They are typically enclosed within
double quotes. For example: “Hello World!”, “I love my India.”

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

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |5
Class Notes on ALGORITHMS and FLOWCHARTS

OPERATORS

ASSIGNMENT OPERATOR

The assignment operation has the following forms:


 variable := expression.
 variable = expression. (In programming languages like C/C++/Java)
In assignment operation, the value of the expression is assigned to the value of the variable
For example:
 x := 5
Here, the value 5 is assigned to the variable x.
 circumference := 2 * 3.141593 * radius
Here, the expression 2*3.141593*radius is evaluated and the result is assigned to the
variable circumference.

MATHEMATICAL OPERATORS
a) Unary Mathematical Operators
The unary operators operate on one operand. The unary mathematical operators are:
 Increment Operator: Increases the value of a number by 1. For example, x++
 Decrement Operator: Decreases the value of a number by 1. For example, x--

b) Binary Mathematical Operators


The binary mathematical operators are:
 + : addition operator
 − : subtraction operator
 * : multiplication operator
 / : division operator
 % : modulus operator that gives remainder after integer division

RELATIONAL OPERATORS
Relational operators allow to compare numeric values or character values. They determine whether
one is greater than, less than, equal to, or not equal to another.
The relational operators are:
Relational Operators Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= or == Equal to
!= Not equal to
Prepared by Moumita Mitra Manna
Dept. of Computer Science, Bangabasi College
Page |6
Class Notes on ALGORITHMS and FLOWCHARTS

Example:
Let us consider that x := 5, y := 10, z := 15. The values of the following expressions will be:
 ( z > y ) : returns True
 ( (y – x) == (z – y)) : returns True
 ( y < x ) : returns False
 ( z != x ) : returns True

LOGICAL OPERATORS
Logical operators connect two or more relational expressions into one or reverse the logic of an
expression.

OPERATOR MEANING
AND connects two expressions into one. Both expressions must be true for the
AND
overall expression to be true.
OR connects two expressions into one. At least one of the expressions must be
OR
true for the overall expression to be true.
NOT operator reverses the "truth" of an expression. It makes a true expression
NOT
false, and a false expression true.

Example:
Let us consider that x := 5, y := 10, z := 15. The values of the following expressions will be:
 ( z > 10 ) AND ( y > 5 ) : returns True
 ( z > 10 ) AND ( y < 5 ) : returns False
 ( z > 10 ) OR ( y < 5 ) : returns True
 ( z < 10 ) OR ( y < 5 ) : returns False
 NOT ( z < 20 ) : returns False
 NOT ( z > 20 ) : returns True

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |7
Class Notes on ALGORITHMS and FLOWCHARTS

DECISION CONTROL STRUCTURES

Decision control is a situation in the algorithm where one has to make a choice of two alternatives
flow of controls by making decision depending on a given condition. They are also called selection
structures.

Depiction in flowchart:

Example

condition Number > 0


True False True False

Task_if_True Task_if_False
PRINT “Positive” PRINT “Negative”

Example:
Algorithm to test whether a number is positive or negative —

Input : One numbers


Output: Whether positive or negative
Step - 1. INPUT a number, x
Step - 2. IF (x ≥ 0) THEN
i. PRINT “Positive”
Step - 3. ELSE
ii. PRINT “ Negative”
( End of If condition of Step 2)
Step - 4. END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |8
Class Notes on ALGORITHMS and FLOWCHARTS

LOOPS
Loops allow repeated execution of certain portions of the algorithm subject to certain conditions.
Each execution within the loop is called iteration. There are two types of loops:
 Entry Controlled Loops: In entry controlled loops, the conditions are checked before the
control enters the loop in each iteration.
 Exit Controlled Loops: In exit controlled loops, the conditions are checked before the
control exits from the loop in each iteration.

Statements within
condition the body of the
loop

False
True

Statements within
condition
the body of the
loop

False
True

Entry Controlled Loop Exit Controlled Loop

Kinds of Loops:
 While Loop
 Do – While Loop
 For Loop

WHILE LOOP
While loop is an entry controlled loop, where the iterations are subject to fulfilment of certain
conditions.
Syntax:
WHILE condition
Statement1
Statement 2
….. …..
( End of while loop )

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
Page |9
Class Notes on ALGORITHMS and FLOWCHARTS

Example:
Algorithm to find H.C.F. of two numbers —

Input : Two numbers


Output: H.C.F.
Step - 1. INPUT two numbers, x and y
// Keep the larger number in Dividend and the smaller number in divisor
Step - 2. IF x > y THEN
(i) Dividend := x
(ii) divisor := y
Step - 3. ELSE
(i) divisor := x
(ii) Dividend := y
( End of If condition of Step 2)
Step - 4. ASSIGN remainder := Dividend % divisor
// Repeatedly divide dividend by divisor while remainder is not 0
Step - 5. WHILE remainder NOT EQUALS 0
(i) Dividend := divisor
(ii) divisor := remainder
(iii) ASSIGN remainder := Dividend % divisor
( End of While loop)
Step - 6. HCF := divisor
Step - 7. PRINT HCF
Step - 8. END

DO WHILE LOOP
Do while loop is an exit controlled loop, , where the iterations are subject to fulfilment of certain
conditions.
Syntax:
DO
Statement1
Statement 2
….. …..
WHILE condition

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 10
Class Notes on ALGORITHMS and FLOWCHARTS

Example:
Algorithm to find the sum of the following series:
1 1 1 1 1
+ + + + + … … … … … … … … … ..
1! 2! 3! 4! 5!
Output : Sum of the series
Step - 1. INITIALISE sum := 0, number := 1
Step - 2. REPEAT
(i) INITIALISE factorial := 1, i := 1
(ii) WHILE i <= number
a) factorial := factorial * i
b) INCREMENT i
(End of While loop)
(iii) term := 1 / factorial
(iv) sum := sum + term
(v) INCREMENT number
WHILE term > 0.000001
Step - 3. PRINT sum
Step - 4. END

FOR LOOP
For Loop is an entry controlled loop which is used when the number of iterations is known in
advance. 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 value of the variable is changed on each
iteration until it reaches the required value.

Syntax:
FOR (initial_state TO terminal_condition, change_in_each_iteration)
Statement1
Statement 2
….. …..
(End of For Loop)

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 11
Class Notes on ALGORITHMS and FLOWCHARTS

Example:
Algorithm to test whether a number is prime or not:

Input : A number, say x


Output : Whether the number is prime or not
Step - 1. INPUT a number, x
Step - 2. INITIALISE, isPrime := True
Step - 3. sq = SQRT(x)
Step - 4. IF x <= 1 THEN
(i) PRINT “Non – Prime”
(ii) EXIT
( End of If condition)
Step - 5. IF x = 2 OR x = 3 THEN
(i) isPrime := True
(ii) GO TO Step 8
(End of If condition)
Step - 6. IF ( x % 2 ) = 0 THEN
(i) isPrime := False
(ii) GO TO Step 8
(End of If condition)
Step - 7. FOR i = 3 TO square_root(x)
(i) IF ( x % i ) = 0 THEN isPrime := False
( End of For Loop)
Step - 8. IF isPrime = True THEN
(i) PRINT “Prime”
Step - 9. ELSE
(i) PRINT “False”
(End of If condition of Step 8)
Step - 10. END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 12
Class Notes on ALGORITHMS and FLOWCHARTS

Sample Algorithms

Problem 1:
Write an algorithm to evaluate the sum of an A. P. Series.

Solution:
Algorithm to find the sum of an A.P. Series:

Inputs : The first term of the series, a


The common difference between the terms, d
The number of terms, n
Output : The sum of the series

Step 1:- INPUT a, n and d.


Step 2:- [ Initialize the sum and the running term ]
2.i. sum ← a
2.ii. term ← a
Step 3:- PRINT a.
Step 4:- FOR ( i = 1 to n-1)
4.i. term ← d + term
4.ii. sum ← sum + term
4.iii. PRINT term.
(end of for loop)
Step 5:- PRINT sum.
Step 6:- END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 13
Class Notes on ALGORITHMS and FLOWCHARTS

Problem 2:
Write an algorithm to display all the Fibonacci numbers within a range. For example, the Fibonacci
numbers within 20 are:
0, 1, 1, 2, 3, 5, 8, 13

Solution:
Algorithm to display the Fibonacci Series:

Inputs : The range


Output : The series

Step 1:- INPUT range.


Step 2:- IF (range < = 0) THEN PRINT “Error” and EXIT
Step 3:- IF range = 1 THEN PRINT 0
Step 4:- IF range = 2 THEN PRINT 0, 1
Step 5:- [Initialize the variables]
i. a ← 0
ii. b ← 1
iii. c ← 0
Step 6:- PRINT a, b.
Step 7:- REPEAT Step 8 to Step 11 WHILE (c ≤ range)
Step 8:- c ← a + b
Step 9:- IF ( c ≤ range) THEN
i. PRINT c
[end of If….then…. structure]
Step 10:- a ← b
Step 11:- b ← c
Step 12:- GO TO Step 7.
Step 13:- END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 14
Class Notes on ALGORITHMS and FLOWCHARTS

Problem 3:
Write an algorithm to input marks in 5 subjects and then find the grade obtained by the student
where grade is given by the following rule:
Average Marks Grade
Average ≥ 80 A
65 ≤ Average < 80 B
50 ≤ Average < 65 C
35 ≤ Average < 50 D
Average < 35 Fail

Solution:
Algorithm to find grade:

Inputs : Marks in five subjects


Output : Grade
Step 1:- INPUT marks_1, marks_2, marks_3, marks_4, marks_5
Step2:- [Calculate the total marks]
Total = marks_1 + marks_2 + marks_3 + marks_4 + marks_5
Step3:- [Calculate the average marks]
Average = Total / 5
Step 4:- IF ( Average >= 80) THEN Grade = ‘A’
Step 5:- IF (Average >= 65 AND Average < 80) THEN Grade = ‘B’
Step 6:- IF (Average >=50 AND Average < 65) THEN Grade = ‘C’
Step 7:- IF (Average >=35 AND Average < 50) THEN Grade = ‘D’
Step 8:- IF (Average < 35) THEN Grade = “Fail”
Step 9:- [ Calculate the status of result]
i. IF ( Grade = ‘F’) THEN PRINT “Status = NOT PROMOTED”
ii. ELSE PRINT “Status = PROMOTED”
[ end of If….else structure]
Step 10:- END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 15
Class Notes on ALGORITHMS and FLOWCHARTS

Problem 4
Write an algorithm to display the prime factors of a number.

Solution
Algorithm for Function isPrime():

Purpose : To test whether an integer passed as an argument is prime or not.


Argument: An integer ,n.
Return : 1 if n is prime, 0 otherwise.
Step 1: -IF (n<=1) THEN RETURN 0
Step 2:- IF (n=2) OR (n=3) THEN RETURN 1
Step 3:- IF (n%2=0) THEN RETURN 0
Step 4:- FOR i←3 to sqrt(n) INCREMENT i by 2 in each iteration
1. IF (n%i)=0 THEN RETURN 0
[End of For loop]
Step 5:- RETURN 1

Algorithm to find Prime Factors of a number:

Purpose : To print the prime factors of a non negative number.


Input : A non negative integer ,num.
Output : Print prime factors of num.
Step 1:-INPUT num.
Step 2:-IF (num<=0) THEN
i. PRINT “Incorrect input”.
Step 3:-ELSE IF (isPrime(num)) THEN PRINT num
Step 4:- ELSE
i. FOR x←2 to num/2
a. IF ( (num% x) =0 AND isPrime(x) ) THEN Print x
[End of For loop]
[End of If…..Else If…structure]
Step 5:-END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 16
Class Notes on ALGORITHMS and FLOWCHARTS

Problem 5
Write an algorithm in C to compute the roots of a quadratic equation.

Solution
Algorithm to find the roots of a quadratic equation
Inputs : The coefficients of the equation a, b, c
Outputs : The roots of the equation
Step 1:- INPUT the coefficients of the quadratic equation, a, b, c
Step 2:- IF a = 0 THEN
1. PRINT “ This is not a quadratic equation.”
2. EXIT
[ End of if structure]
Step 3:- COMPUTE the determinant d = (b*b)-(4*a*c)
Step 4:- IF (d > 0) THEN
1. PRINT “The roots are real and distinct.”
2. COMPUTE the first root x = ((-b + sqrt(d)) / 2 * a)
3. COMPUTE the second root y= ((-b- sqrt(d)) /2 * a)
4. PRINT x and y.
Step 5:- ELSE IF (d = 0) THEN
1. PRINT “ The roots are equals.”
2. COMPUTE the roots x = y = ( -b / (2 * a))
3. PRINT x.
Step 6:- ELSE
1. ASSIGN d = -d
2. PRINT “The roots are imaginary.”
3. COMPUTE s = (- b / (2 * a))
4. COMPUTE m = ( sqrt(d) / 2 * a)
5. The first root x = s + im and second root y = s – im
6. PRINT the values of x and y.
[ End of if… Then…Else if structure]

Step 7:- END

Prepared by Moumita Mitra Manna


Dept. of Computer Science, Bangabasi College
P a g e | 17

You might also like