S1 ATP Module II Algorithm and Pseudocode
S1 ATP Module II Algorithm and Pseudocode
PYTHON
MODULE II:
ALGORITHM AND PSEUDOCODE
Reference:
Ajeesh Ramanujan, Narasimhan T, ALGORITHMIC THINKING WITH PYTHON
* - Evaluate an expression, d=a+b*c, find simple interest, determine the larger of two
numbers, determine the smallest of three numbers, determine the grade earned by a student
based on KTU grade scale (using if-else and case structures), print the numbers from 1 to 50
in descending order, find the sum of n numbers input by the user (using all the three loop
variants), factorial of a number, largest of n numbers (Not to be limited to these exercises.
More can be worked out if time permits).
1
2. ALGORITHM AND PSEUDOCODE REPRESENTATION
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.
As the name indicates, pseudocode is not a true program and thus is independent 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.
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.
2
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.
Wondering why pseudocodes are important? Here are a few motivating reasons:
3
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.
Constructs of a pseudocode
A good pseudocode should follow the structured programming approach. Structured 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 repetition (loop) are three programming constructs that allow for
linear control flow. These are also known as single entry – single exit constructs.
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.
Operator Meaning
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to
4
2.3.1. Sequencing:
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.
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
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
if (condition)
true_instructions
endif
5
If the test condition is evaluated to True, the statements denoted by true_instructions are executed.
Otherwise, those statements are skipped.
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.
Example 2.2. The pseudocode PersonType(age) checks if a person is a major or not.
PersonType(age)
6
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
Example 2.3. The pseudocode CompareVars(x, y) compares two variables x and y and prints the
relation between them.
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
7
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 compared with value2. If there is a match here, block2 is executed and the
structure 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 expression 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.
8
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
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:
9
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
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. 2. In the while loop, the condition is tested at the beginning; in the repeatuntil 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
10
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 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 .
11
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 below lists some examples of for loops. In these examples, var is the loop variable.
Sample problems:*
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. 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.
12
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 a b . Use
the fact that a b is multiplying a with itself b times.
13