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

Algorithms, Pseudocodes, And Flowchart

Uploaded by

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

Algorithms, Pseudocodes, And Flowchart

Uploaded by

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

Chapter 2

Algorithms, pseudocodes,
and flowcharts

“When you choose an algorithm, you choose a point of view”


– Anonymous

“An Algorithm is a storytellers’ script while Pseudocode is the builders’ blueprint”


– Anonymous

2.1 Algorithms and pseudocodes


An algorithm describes a systematic way of solving a problem. It is a step-by-
step procedure that produces an output when given the necessary inputs. An
algorithm uses pure English phrases or sentences to describe the solution to a
problem. A Pseudocode is a high-level representation of an algorithm that
uses a mixture of natural language and programming language-like syntax. It
is more structured than an algorithm in that it uses mathematical expressions
with English phrases to capture the essence of a solution concisely. You can also
use programming constructs (See Section 2.1.2 below) in a pseudocode which
are not permitted in an algorithm in a strict sense.
As the name indicates, pseudocode is not a true program and thus is inde-
pendent of any programming language. It is not executable rather helps you
understand the flow of an algorithm.
Confused between algorithms and pseudocodes? Let us take an example. We
will now write an algorithm and a pseudocode to evaluate an expression, say
d = a + b ∗ c. Here a, b, c, and d are known as variables. Simply put, a variable
is a name given to a memory location that stores some data value. First, let us
look at the algorithm for the expression evaluation.

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.

The following is the pseudocode to evaluate the same expression.

Evaluate-Pseudo
1 Start
2 Read(a, b, c)
3 d=a+b∗c
4 Print(d)
5 Stop

In a pseudocode, Read is used to read input values. Print is used to print


a message. The message to be printed should be enclosed in a pair of double
quotes. For example,
Print(“Hello folks!!”)
prints
Hello folks!!
To print the value of a variable, just use the variable name (without quotes). In
the above example, Print(d) displays the value of the variable d.
Although pseudocode and algorithm are technically different, these words
are interchangeably used for convenience.

2.1.1 Why pseudocodes?


Wondering why pseudocodes are important? Here are a few motivating reasons:
1. Ease of understanding: Since the pseudocode is programming language
independent, novice developers can also understand it very easily.
2. Focus on logic: A pseudocode allows you to focus on the algorithm’s logic
without bothering about the syntax of a specific programming language.
3. More legible: Combining programming constructs with English phrases
makes pseudocode more legible and conveys the logic precisely.
4. Consistent: As the constructs used in pseudocode are standardized, it is
useful in sharing ideas among developers from various domains.
28 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

Table 2.1: Relational operators

Operator Meaning
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to

5. Easy translation to a program: Using programming constructs makes


mapping the pseudocode to a program straightforward.

6. Identification of flaws: A pseudocode helps identify flaws in the solution


logic before implementation.

2.1.2 Constructs of a pseudocode


A good pseudocode should follow the structured programming approach. Struc-
tured coding aims to improve the readability of pseudocode by ensuring that
the execution sequence follows the order in which the code is written. Such a
code is said to have a linear flow of control. Sequencing, selection, and repeti-
tion (loop) are three programming constructs that allow for linear control flow.
These are also known as single entry – single exit constructs.

R When it is said that “the pseudocode is executed”, it just means that


the pseudocode instructions are interpreted. It doesn’t denote the actual
execution on a computer.

In the sequence structure, all instructions in the pseudocode are executed


(exactly) once without skipping any. On the other hand, with selection and
loop structures, it is possible to execute certain instructions repeatedly or even
skip some. In such structures, the decision as to which statements are to be
executed or whether the execution should repeat will be determined based on
the outcome of testing a condition. We use special symbols called relational
operators to write such conditions. The various relational operators are listed
in Table 2.1. It is also possible to combine two or more conditions using logical
operators like “AND” (&&), “OR” (||). Eg: a > b AND a > c.

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

The statement S1 is executed first, which is then followed by statement S2, so


on and so forth, Sn until all the instructions are executed. No instruction is
skipped and every instruction is executed only once.

2.1.2.2 Decision or Selection

A selection structure consists of a test condition together with one or more


blocks of statements. The result of the test determines which of these blocks
is executed. There are mainly two types of selection structures, as discussed
below:

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

If the test condition is evaluated to True, the statements denoted by true_instructions


are executed. Otherwise, those statements are skipped.

Example 2.1. The pseudocode CheckPositive(x) checks if an input value x


is positive.

CheckPositive(x)
1 if (x > 0)
2 Print(x,“ is positive”)
3 endif

A.2 if else structure


The general form is given below:
30 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

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.

Example 2.2. The pseudocode PersonType(age) checks if a person is a major


or not.

PersonType(age)
1 if (age >= 18)
2 Print(“You are a major”)
3 else
4 Print(“You are a minor”)
5 endif

A.3 if else if else structure


When a selection is to be made out of a set of more than two possibilities, you
need to use the if else if else structure, whose general form is given below:

if (condition1 )
true_instructions1
else if (condition2 )
true_instructions2
else
false_instructions
endif

Here, if condition1 is met, true_instructions1 will be executed. Else


condition2 is checked. If it evaluates to True, true_instructions2 will be
selected. Otherwise false_instructions will be executed.

Example 2.3. The pseudocode CompareVars(x, y) compares two variables x


and y and prints the relation between them.
2.1. ALGORITHMS AND PSEUDOCODES 31

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

Example 2.4. The pseudocode PrintDirection(dir) prints the direction


name based on the value of a character called dir.

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

2.1.2.3 Repetition or loop


When a certain block of instructions is to be repeatedly executed, we use the
repetition or loop construct. Each execution of the block is called an iteration
or a pass. If the number of iterations (how many times the block is to be
executed) is known in advance, it is called definite iteration. Otherwise, it
is called indefinite or conditional iteration. The block that is repeatedly
executed is called the loop body. There are three types of loop constructs as
discussed below:

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

the loop body is repeated as long as condition evaluates to False. When


the condition evaluates to True, the loop is exited. The pseudocode form of
repeat-until loop is shown below.

repeat
false_instructions
until (condition)

There are two major differences between while and repeat-until loop con-
structs:

1. In the while loop, the pseudocode continues to execute as long as the


resultant of the condition is True; in the repeat-until loop, the looping
process stops when the resultant of the condition becomes True.

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:

for var = begin to end


loop_instructions
endfor

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.

for var = begin downto end


loop_instructions
endfor

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 .

for var = begin to end by step


loop_instructions
endfor

Table 2.2 lists some examples of for loops. In these examples, var is the loop
variable.

Table 2.2: for loop examples

Loop construct Description Values taken by var


for var = 1 to 10 var gets incremented by 1 till it reaches 10 1, 2, · · · 9, 10
for var = 10 downto 1 var gets decremented by 1 till it reaches 1 10, 9, · · · 2, 1
for var = 2 to 20 by 2 var gets increased by 2 till it reaches 20 2, 4, · · · 18, 20
for var = 20 downto 2 by 2 var gets decreased by 2 till it reaches 2 20, 18, · · · 4, 2

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

Table 2.3: The different flowchart symbols

Flowchart symbol Description


Flattened ellipse indicates the start and end of a
module.

Rectangle is used to show arithmetic calculations.

Parallelogram denotes an input/output operation.

Diamond indicates a decision box with a condition


to test. It has two exits. One exit leads to a block
specifying the actions to be taken when the tested
condition is True and the other exit leads to a
second block specifying the actions for False case.
Rectangle with vertical side-lines denotes a
module. A module is a collection of statements
written to achieve a task. It is known by the name
function in the programming domain.

count Hexagon denotes a for loop. The symbol shown


A B here is the representation of the loop:
S for count = A to B by S.

Flowlines are indicated by arrows to show the


direction of data flow. Each flowline connects two
blocks.

This indicates an on-page connector. This is used


when one part of a long flowchart is drawn on one
column of a page and the other part in the other
column of the same page.

This indicates an off-page connector. This is used


when the flowchart is very long and spans multiple
pages.
36 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

2.3 Solved problems - Algorithms and


Flowcharts
Problem 2.1 To find simple interest.
Solution:
See Figure 2.1 for the algorithm and flowchart.

Start

Read(principal , rate, years)


SimpleInterest
1 Start
2 Read(principal , rate, years)
SI = (principal ∗ rate ∗ years)/100
3 SI = (principal ∗ rate ∗ years)/100
4 Print(SI )
5 Stop.
Print SI

Stop

Figure 2.1: To find simple interest

• 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.

Problem 2.2 To determine the larger of two numbers.


Solution:
See Figure 2.2 for the algorithm and flowchart.
2.3. SOLVED PROBLEMS - ALGORITHMS AND FLOWCHARTS 37

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

Figure 2.2: To find the larger of two numbers

• First, read two numbers from the user and store them in the variables a
and b respectively.

• Next, compare these two numbers using an if-else statement.


• Check whether a is greater than b.
– If this condition is True, assign the value of a to the variable large.
• Otherwise, the control moves to the else part, where the value of b is
assigned to large.
• Finally, the value of large is printed, which is the largest of the two num-
bers.

Problem 2.3 To determine the smallest of three numbers.


Solution:
See Figure 2.3 for the algorithm and flowchart.
38 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

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

Figure 2.3: To find the smallest of three numbers

• 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.

• Using a second if statement, check whether c is less than small.

– If so, the value of c is assigned to small.

• Finally, small is printed.

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?

3 if (age < 10)


4 fare = 7
fare = 7
5 else if (age < 60) False True
age < 60?
6 fare = 10
7 else
8 fare = 5 fare = 5 fare = 10
9 endif
10 Print(fare)
11 Stop
Print(fare)

Stop

Figure 2.4: To determine the entry fare in a zoo

• Accept age from the user.

• 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.

• Finally, the fare value is printed.

Problem 2.5 To print the colour based on a code value as follows:


40 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

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

‘R’ ‘G’ ‘B’ default


Print(“Red”) Print(“Green”)

Print(“Blue”) Print(“Wrong code”)

Stop

Figure 2.5: To print colors based on a code value


2.3. SOLVED PROBLEMS - ALGORITHMS AND FLOWCHARTS 41

• Read the code (a character constant) from the user.


• The value of code is matched against a number of case constants (R, G, B
as per the question).
• If the code is ’R’, the statements associated with it are executed until the
break statement is encountered (i.e. ”Red” is printed here). A break
statement moves the control out of the case structure.
• A similar execution happens if the value of code is G or B. If code is ’G’,
”Green” is printed, and ”Blue” is printed if code is ’B’.
• If the user inputs any other character other than ’R’, ’G’, or ’B’, the
default statement is executed.

Problem 2.6 To print the numbers from 1 to 50 in descending order.

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

Figure 2.6: To print numbers in descending order

• 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 condition, count >= 1 is checked, and since it evaluates to True,


the body of the loop is executed (49 is printed), and again count is decre-
mented.

• 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.

Problem 2.7 To find the factorial of a number.


Solution:The factorial of a number n is defined as n! = n×n−1×· · · · · ·×2×1.
See Figure 2.7 for the pseudocode and flowchart.

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

Figure 2.7: To find the factorial of a number

• Read n from the user, whose factorial is to be calculated.

• Initialize fact to 1

• Write a loop, with the loop control variable var initialized to n.

– 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.

Problem 2.8 To determine the largest of n numbers.

Solution:See Figure 2.8 for pseudocode and flowchart.

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

• Read n from the user.


• Along with that, read a single number num from the user and assign a
variable large with num. That is the first one among the set of input
integers is assumed to be the largest.
• Initialize a loop, with the loop control variable count being assigned the
value of 1.
44 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

• During every iteration of the loop,


– obtain a number from the user and keep it in num variable
– num is checked against large
– If num > large, update largeto num
• This is repeated as long as the value of count is less than or equal to n -
1.
– You need to iterate the loop only n - 1 times since you received the
first integer before entering the loop.
• After all iterations, the largest value is displayed.

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

sum = sum + age


count = count + 1
Print(average)

Stop

Figure 2.9: To determine the average age using while loop

• Initialize the variables sum and count to 0.


• Read the age of the first student and keep it in age variable.
2.3. SOLVED PROBLEMS - ALGORITHMS AND FLOWCHARTS 45

• 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.

Problem 2.10 Redo Problem 2.9 using repeat-until loop construct.

Solution: See Figure 2.10 for flowchart and pseudocode.

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

• Initialize sum, count to 0.


• Read age from the user.
• Write the repeat-until loop:
• Inside the loop:

– add age value to sum


– increment Count
– read the next age value
• Continue the loop until the user inputs a 0 for age.

• 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 ’?

gtotal = gtotal + height btotal = btotal + height


gcount = gcount + 1 bcount = bcount + 1

var

bavg = btotal /bcount


gavg = gtotal /gcount

Print(gavg, bavg)

Stop

Figure 2.11: To find the average height of boys and girls


48 CHAPTER 2. ALGORITHMS, PSEUDOCODES, AND FLOWCHARTS

• Input n from the user.

• 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.

• During each iteration:

– Read gender and height


– If the gender is ’M ’, add the input height to btotal and increment
bcount
– Otherwise, add the input height to gtotal and increment gcount

• 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.

• Finally print the average values.

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:

1. to find the area and circumference of a circle.


2. to find the area of a triangle given its three sides.
3. to find the area and perimeter of a rectangle.
4. to find the area of a triangle given its length and breadth.
2.5. EXERCISES 49

2. If the three sides of a triangle are input, write an algorithm to check


whether the triangle is isosceles, equilateral, or scalene.
3. Write a switch statement that will examine the value of flag and print
one of the following messages, based on the value assigned to the flag.

Flag value Message


1 HOT
2 LUKE WARM
3 COLD
Any other value OUT OF RANGE

4. Write algorithms for the following:


(a) to display all odd numbers between 1 and 500 in descending order.
(b) to compute and display the sum of all integers that are divisible by
6 but not by 4 and that lie between 0 and 100.
(c) to read a value, and do the following: If the number is even, halve
it; if it’s odd, multiply by 3 and add 1. Repeat this process until the
value is 1, printing out each value.
5. Write an algorithm that inputs two values a and b and that finds ab . Use
the fact that ab is multiplying a with itself b times.

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.

7. Draw flowcharts for the following:


(a) to find the volume of a hemisphere by inputting the radius.
(b) to find the profit or loss incurred by getting the cost price and selling
price of an item. Note that you are not asked to determine whether
profit or loss is incurred but rather the value of profit or loss. Assume
cost price ̸= selling price.
(c) to find the average of a list of numbers entered by the user. The user
will stop the input by giving the value −999.

You might also like