Algorithms, Pseudocodes, And Flowchart
Algorithms, Pseudocodes, And Flowchart
Algorithms, pseudocodes,
and flowcharts
26
2.1. ALGORITHMS AND PSEUDOCODES 27
Evaluate-Algo
1 Start
2 Read the values of a, b and c.
3 Find the product of b and c.
4 Store the product in a temporary variable temp.
5 Find the sum of a and temp.
6 Store the sum in d.
7 Print the value of d.
8 Stop.
Evaluate-Pseudo
1 Start
2 Read(a, b, c)
3 d=a+b∗c
4 Print(d)
5 Stop
Operator Meaning
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to
2.1.2.1 Sequence
This is the most elementary construct where the instructions of the algorithm
are executed in the order listed. It is the logical equivalent of a straight line.
Consider the code below.
2.1. ALGORITHMS AND PSEUDOCODES 29
S1
S2
S3
.
.
Sn
A if structure
There are three variations of the if-structure:
A.1 if structure
The general form of this structure is:
if (condition)
true_instructions
endif
CheckPositive(x)
1 if (x > 0)
2 Print(x,“ is positive”)
3 endif
if (condition)
true_instructions
else
false_instructions
endif
This structure contains two blocks of statements. If the test condition is met,
the first block (denoted by true_instructions) is executed and the algorithm
skips over the second block (denoted by false_instructions). If the test
condition is not met, the first block is skipped and only the second block is
executed.
PersonType(age)
1 if (age >= 18)
2 Print(“You are a major”)
3 else
4 Print(“You are a minor”)
5 endif
if (condition1 )
true_instructions1
else if (condition2 )
true_instructions2
else
false_instructions
endif
CompareVars(x, y)
1 if (x > y)
2 Print(x,“is greater than”,y)
3 else if (x < y)
4 Print(y,“is greater than”,x)
5 else
6 Print(“The two values are equal”)
7 endif
There is no limit to the number of else if statements, but in the end, there
has to be an else statement. The conditions are tested one by one starting from
the top, proceeding downwards. Once a condition is evaluated to be True, the
corresponding block is executed, and the rest of the structure is skipped. If
none of the conditions are met, the final else part is executed.
B Case Structure
The case structure is a refined alternative to if else if else structure. The
pseudocode representation of the case structure is given below.
The general form of this structure is:
caseof (expression)
case 1 value1 :
block1
case 2 value2 :
block2
..
.
default :
default_block
endcase
The case structure works like this: First, the value of expression (you can
also have a single variable in the place of expression) is compared with value1 .
If there is a match, the first block of statements denoted as block1 will be
executed. Typically, each block will have a break at the end which causes the
case structure to be exited.
If there is no match, the value of the expression (or of the variable) is com-
pared with value2 . If there is a match here, block2 is executed and the struc-
ture is exited at the corresponding break statement. This process continues
until either a match for the expression value is found or until the end of the
cases is encountered. The default_block will be executed when the expres-
sion does not match any of the cases.
If the break statement is omitted from the block for the matching case, then
the execution continues into subsequent blocks even if there is no match in the
subsequent blocks, until either a break is encountered or the end of the case
structure is reached.
32 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS
PrintDirection(dir)
1 caseof (dir)
2 case ‘N’:
3 Print(“North”)
4 break
5 case ‘S’:
6 Print(“South”)
7 break
8 case ‘E’:
9 Print(“East”)
10 break
11 case ‘W’:
12 Print(“West”)
13 break
14 default :
15 Print(“Invalid direction code”)
16 endcase
A while loop
A while loop is generally used to implement indefinite iteration. The general
form of the while loop is as follows:
while (condition)
true_instructions
endwhile
Here, the loop body (true_instructions) is executed repeatedly as long as
condition evaluates to True. When the condition is evaluated as False, the
loop body is bypassed.
B repeat-until loop
The second type of loop structure is the repeat-until structure. This type of
loop is also used for indefinite iteration. Here the set of instructions constituting
2.1. ALGORITHMS AND PSEUDOCODES 33
repeat
false_instructions
until (condition)
There are two major differences between while and repeat-until loop con-
structs:
2. In the while loop, the condition is tested at the beginning; in the repeat-
until loop, the condition is tested at the end. For this reason, the while
loop is known as an entry controlled loop and the repeat-until loop is
known as an exit controlled loop.
You should note that when the condition is tested at the end, the instructions
in the loop are executed at least once.
C for loop
The for loop implements definite iteration. There are three variants of the for
loop. All three for loop constructs use a variable (call it the loop variable) as a
counter that starts counting from a specific value called begin and updates the
loop variable after each iteration. The loop body repeats execution until the
loop variable value reaches end . The first for loop variant can be written in
pseudocode notation as follows:
Here, the loop variable (var ) is first assigned (initialized with) the value begin.
Then the condition var <= end is tested. If the outcome is True, the loop
body is executed. After the first iteration, the loop variable is incremented
(increased by 1). The condition var <= end is again tested with the updated
value of var and the loop is entered (loop body is executed), if the condition
evaluates to True. This process of updating the loop variable after an iteration
and proceeding with the execution if the condition (tested with the updated
value of the loop variable) evaluates to True continues until the counter value
becomes greater than end . At that time, the condition evaluates to False and
the loop execution stops.
In the second for loop variant, whose pseudocode syntax is given below, the
loop variable is decremented (decreased by 1) after every iteration. And the
34 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS
condition being tested is var >= end. Here, begin should be greater than or
equal to end , and the loop exits when this condition is violated.
It is also possible to update the loop variable by an amount other than 1 after
every iteration. The value by which the loop variable is increased or decreased
is known as step. In the pseudocode shown below, the step value is specified
using the keyword by .
Table 2.2 lists some examples of for loops. In these examples, var is the loop
variable.
2.2 Flowcharts
A flowchart is a diagrammatic representation of an algorithm that depicts how
control flows in it. Flowcharts are composed of various blocks interconnected
by flow-lines. Each block in a flowchart represents some stage of processing in
the algorithm. Different types of blocks are defined to represent the various
programming constructs of the algorithm.
Flow lines indicate the order in which the algorithm steps are executed. The
flow lines entering a block denote data (or control) flow into the block and the
flow lines emerging from a block denote data (control) outflow. Most blocks
have only single incoming and outgoing flow lines. The exception is for blocks
representing selection and loop constructs. Such blocks have multiple exits, one
for each possible outcome of the condition being tested and each such outcome
is called a branch.
Table 2.3 lists some commonly used flowchart symbols and their descriptions.
2.2. FLOWCHARTS 35
Start
Stop
• Read the principal amount, interest rate, and period values. Store them
as three variables: principal, rate, and years respectively.
• Multiply principal, rate and years and divide the result by 100 to obtain
the simple interest, which is stored in the variable SI.
– Division by 100 is necessary since rate is input as a percentage(7%
instead of 0.07).
• Finally, the value of SI is displayed on the terminal.
Start
Read(a, b)
LargerTwo
1 Start False
a > b?
True
2 Read(a, b)
3 if (a > b)
4 large = a large = b large = a
5 else
6 large = b
7 endif
8 Print(large) Print(large)
9 Stop.
Stop
• First, read two numbers from the user and store them in the variables a
and b respectively.
Start
Read(a, b, c)
False True
a < b?
SmallestThree
1 Start
2 Read(a, b, c) small = b small = a
3 if (a < b)
4 small = a
5 else
6 small = b
7 endif
8 if (c < small ) True
c < small ?
9 small = c
10 endif
11 Print(small ) small = c
12 Stop. False
Print(small )
Stop
• Similar to the previous problem, input three numbers and store them in
variables a, b, and c respectively.
• To solve this problem, first find the smaller of the two numbers a and b
and then compare that smaller number with the third variable c.
• The first if statement determines the smaller between a and b and keeps
it in small.
Problem 2.4 To determine the entry-ticket fare in a zoo based on age as follows:
2.3. SOLVED PROBLEMS - ALGORITHMS AND FLOWCHARTS 39
Age Fare
< 10 7
>= 10 and < 60 10
>= 60 5
Solution:
See Figure 2.4 for the pseudocode and flowchart.
Start
Read(age)
TicketFare
1 Start False True
2 Read(age) age < 10?
Stop
• First check whether age is less than 10. If so, fare is assigned the value 7.
• If the condition is False, the next condition is checked. If age >= 10 and
age < 60, fare gets the value 10.
• If the above condition also turns out to be False (i.e. age >= 60), else
statement is executed, and fare gets the value 5.
Grade Message
R Red
G Green
B Blue
Any other value Wrong code
Solution:
Figure 2.5 for the pseudocode and flowchart.
PrintColour
1 Start
2 Read(code)
3 caseof (code)
4 case ‘R’:
5 Print(“Red”)
6 break
7 case ‘G’:
8 Print(“Green”)
9 break
10 case ‘B’:
11 Print(“Blue”)
12 break
13 default :
14 Print(“Wrong code”)
15 endcase
16 Stop
Start
Read(code)
caseof
code
Stop
Solution:
See Figure 2.6 for pseudocode and flowchart.
Start
count
50 1
PrintDown -1
1 Start
2 for count = 50 downto 1
Print(count)
3 Print(count)
4 endfor
5 Stop
count
Stop
• The count variable is initially assigned 50 and the condition, count >= 1
(i.e. 50 >= 1) is checked.
• Since it evaluates to True, print statement is executed (Body of for loop
in this question).
• ‘downto’ decrements the value of count by 1 i.e. count now becomes 49.
42 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS
• The above step repeats until count becomes 0 (in which case, the condition
evaluates to False) and you stop. The sequence thus printed is 50 49 48
· · · 1.
Start
Read(n)
fact = 1
Factorial
1 Start
2 Read(n) var
n 1
3 fact = 1 -1
4 for var = n downto 1
5 fact = fact ∗ var
fact = fact ∗ var
6 endfor
7 Print(fact)
8 Stop
var
Print(fact)
Stop
• Initialize fact to 1
– For each iteration of the loop, multiply the value inside fact variable
with var and store it infact.
2.3. SOLVED PROBLEMS - ALGORITHMS AND FLOWCHARTS 43
• This is continued until the value of var becomes greater than or equal to
1, with var being decremented by 1 after every iteration.
• At the end of all iterations, fact is printed.
Start
Read(n, num)
large = num
count
LargeN 1 n−1
1
1 Start
2 Read(n, num) Read(num)
3 large = num
4 for count = 1 to n − 1
5 Read(num)
6 if (num > large) True
num > large?
7 large = num
8 endif
large = num
9 endfor False
10 Print(large)
11 Stop
count
Print(large)
Stop
‘
Figure 2.8: To find the largest of n numbers
Problem 2.9 To determine the average age of students in a class. The user
will stop giving the input by giving the age as 0.
Solution:See Figure 2.9 for pseudocode and flowchart.
Start
AverageAgev1
1 Start sum = 0
2 sum = 0 count = 0
3 count = 0
4 Read(age) Read(age)
5 while (age!=0)
6 sum = sum + age
7 count = count + 1
8 Read(age) while False
age!=0
9 endwhile
10 average = sum/count
11 Print(average)
True
12 Stop average = sum/count
Stop
• Write a while loop that will run until age is not equal to zero.
• In every iteration,
– add the age value to sum and increment count by 1
– read the next value of age
• After getting out of the loop, determine the average age by dividing sum
by count.
• Print the average value.
Start
sum = 0
count = 0
Read(age)
AverageAgev2 repeat
1 Start sum = sum + age
count = count + 1
2 sum = 0
3 count = 0
4 Read(age) Read(age)
5 repeat
6 sum = sum + age
7 count = count + 1 False
8 Read(age)
until
9 until (age == 0) age == 0
10 average = sum/count
11 Print(average)
12 Stop True
average = sum/count
Print(average)
Stop
Figure 2.10: To determine the average age using repeat until loop
46 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS
• After getting out of the loop, determine the average age by dividing sum
by count.
• Print the average value.
Problem 2.11 To find the average height of boys and average height of girls in
a class of n students.
Solution: See Figure 2.11.
AverageHeight
1 Start
2 Read(n)
3 btotal = 0
4 bcount = 0
5 gtotal = 0
6 gcount = 0
7 for var = 1 to n
8 Read(gender , height)
9 if (gender = = ‘M ’)
10 btotal = btotal + height
11 bcount = bcount + 1
12 else
13 gtotal = gtotal + height
14 gcount = gcount + 1
15 endif
16 endfor
17 bavg = btotal /bcount
18 gavg = gtotal /gcount
19 Print(bavg, gavg)
20 Stop
2.3. SOLVED PROBLEMS - ALGORITHMS AND FLOWCHARTS 47
Start
Read(n)
bcount = 0
gcount = 0
btotal = 0
gtotal = 0
var
1 n
1
Read(gender , height)
False True
gender == ‘M ’?
var
Print(gavg, bavg)
Stop
• Define variables btotal, bcount, gtotal, and gcount to store the total height
of boys, number of boys, total height of girls and number of girls respec-
tively. Initialize all the four variables to 0
• Write a loop that prompts the user for the relevant inputs for all the n
students.
• After getting out of the loop, determine the average height of the boys,
bavg by dividing btotal with bcount. In a similar way, calculate the average
height of the girls, gavg by dividing gtotal with gcount.
2.4 Conclusion
In this chapter, we’ve explored the foundational elements of algorithms,
flowcharts, and pseudocode — the essential tools in the development of effi-
cient and effective programs. Algorithms provide a clear, step-by-step approach
to problem-solving, while flowcharts offer a visual representation that aids in
understanding the logical flow. Pseudocode serves as an intermediary step,
bridging the gap between the abstract algorithm and the actual code, making
it easier to translate ideas into executable code. Together, these tools help in
breaking down complex problems into manageable parts, ensuring clarity and
precision in programming. Mastering these concepts is crucial for anyone aim-
ing to develop robust software solutions. As you move forward, these skills will
serve as a solid foundation for tackling more complex problems.
2.5 Exercises
1. Write algorithms for the following:
6. You visit a shop to buy a new mobile. In connection with the festive
season, the shop offers a 10% discount on all mobiles. In addition, the
shop also gives a flat exchange price of | 1000 for old mobiles. Draw a
flowchart to input the original price of the mobile and print its selling
price. Note that all customers may not have an old mobile for exchange.