Pseudocodes & Algorithms
Pseudocodes & Algorithms
Objective
Discuss imitation of the code before writing the actual one.
Explain the structures available in various programming languages.
Analyze the logic for writing computer programs.
INTRODUCTION
Most often a pseudocode is required to write a rough draft of the code before writing the actual program.
Pseudocode is a detailed description of an algorithm or computer program with more focus on readability and
understandability and less focus on technical requirements. It is written in a formally styled natural language.
It can be best described as a combination of code and English language.
The advantage of writing pseudocodes is that it provides the advantages of an informal language like English
along with the precision of code. This high level description helps the programmer to easily transform it into a
code, since it mimics the actual code. It is more focused on writing the logic of the program rather than the
code.
WRITING PSEUDOCODES
A computer program can perform the following list of operations like:
Receive information
Output information
Perform various operations
Assign values
Compare two or more options and select one
Repeat a group of steps
For receiving or inputting information in a computer program the get, "read" and "input" words can be use
I. The input can be taken from any source including keyboard, disk or any other device. Any value taken as
input from the user needs to be stored somewhere which is generally a variable. For example, to input the
marks of a student we write:
Read marks
Where marks is a variable that stores the value entered by the user.
For displaying the output of a computer program, display", "print "output, put" or "write words can he
used. The value contained in the variable is printed on the respective device, which could again be any output
device including monitor, file or disk.
For example, to display the value stored in the variable marks. we can write.
Print marks
Display marks
Write marks
This statement prints the value stored in the variable marks. The value can be entered by the user or assigned
to the variable. To assign some value to a variable, a simple assignment statement can be written as follows:
a= 5
where the value at the right-hand side of the equal to operator is assigned to the variable a.
The right-hand side can also contain an expression, which is computed and assigned to the left-hand side.
For example,
a= 5*2
"Calculate" and "compute" words can be used for any kind of arithmetic operations. These operations can be
specified using words or mathematical symbols. The basic operators are also used, since pseudocode is a
mimic of the actual code.
The lists of various mathematical operators that can be used in a pseudocode are as follows. Also the order of
operation of any operation in any expression is given from top to bottom.
Although pseudocode is written in an in Formal language, it is still necessary to follow certain rules and
conventions to make it mimic the code. Following are certain points to be kept in mind to write pseudocode:
The steps of writing the sequence, selection and repetition statements in pseudocodes are discussed below.
Sequence construct is a list of statements that are executed sequentially moving from one step to another.
Each action is performed one after the other from top to bottom and left to right as written. The statements are
executed without any condition checking. A sequence construct can be a part of selection and repetition
statements as well. For example, the sequence of statements performed to find the simple interest can be
written as follows:
Read principal
Read rate
Read time
Compute si = (principal*rate*time)/100
Print si
All the statements in the above pseudocode for computing simple interest are executed one after the other in
sequence in the order in which they are written.
Instead of reading the values of principal, rate and time in 3 separate statements, a single statement can also be
written. For example,
The statement
Print si
Most often is required in a code to compare one value with another for making selection between different
choices. Thus, sequence allows selecting a particular option from a given set of choices.
For making comparisons, relational operators are used. Table 1.2 shows the relational operators used to make
comparisons.
Comparisons done using relational operators evaluate to either true or false. These are also called Boolean
expressions since they return in a Boolean value. A Boolean expression always consists of two alternatives.
Assuming there are two variables x and y containing the values 4 and 5 respectively, some of the comparison
statements are given as below:
The comparison for the given values is done using the lf-End if construct. It allows the branching of code with
the evaluation of the Boolean expression. If the Boolean expression returns true, then the set of statements
associated with the true branch is executed. Otherwise, the set of statement with the false branch is executed
(if given).
For example, pseudocode to check whether a given number is odd or even.
Read number
D=number%2
If d==0
End if
If In the above pseudocode, a number is taken as input from the user and stored in the variable number. The
value of the number is divided by 2 and the remainder is stored in the variable d.
Now the decision or selection control statement checks whether the value of the remainder is 0 or not. If it is
0, the print statement is executed and prints Number is even on the output screen. II it is not equal to 0, it
terminates the code. Selection statement allows the programmer to compare the value of d with 0 and then
make a decision.
Sometimes, it is required to print another message if the comparison is not true. In this situation if-Else-End if
construct is used.
Read number
D=number%2
If d==0
else
End if
Boolean expressions can be made more complex with the use of logical operators. The different logical
operators that are used in a Boolean expression are given in Table 1.3.
Suppose there is a situation where a decision has to be made based the condition if a given number is even and
also a multiple of seven. in such, a scenario, the AND operator can be used. It will check both the conditions
of even number and multiple of seven.
Read number
End if
Number %2==0
And
Number %7==0
Now when both the expressions are true with the true branch is executed.
After discussing the concepts of pseudocodes, let us talk about their advantages and disadvantages.
Advantages
It is not visual.
Since there is no standard, pseudocode written by two persons will differ.
An algorithm is a well defined sequence of steps that provides a solution for a given problem, while a
pseudocode is one of the methods that can be used to represent an algorithm. While algorithms can be written
in natural language, pseudocode is written in a format that is closely related to high level programming
language structures. But pseudocode does not use specific programming language syntax and therefore could
be understood by programmers who are familiar with different programming languages. Additionally,
transforming an algorithm presented in pseudocode to programming code could be much easier than
converting an algorithm written in natural language.
Example 1: Write pseudo code that reads two numbers and multiplies them together and print out their
product.
Example 2: Write pseudo code that tells a user that the number they entered is not a 5 or a 6.
Read isfive
If(isfive = 5)
Write "your number is 5"
Else if (isfive = 6)
Write "your number is 6"
Else
Write "your number is not 5 or 6"
OR
Read isfive
If(isfive = 5 or isfive = 6)
Write "your number is a 5 or 6"
Else
Write "your number is not 5 or 6"
Example 3: Write pseudo code that performs the following: Ask a user to enter a number. If the number is
between 0 and 10, write the word blue. If the number is between 10 and 20, write the word red. if the number
is between 20 and 30, write the word green. If it is any other number, write that it is not a correct color option.
Example 4: Write pseudo code to print all multiples of 5 between 1 and 100 (including both 1 and 100).
Set x to 1
While(x < 20)
WRITE x
x = x*5
ALGORITHMS
We all know that computer is an electronic device and it performs the tasks as per the set of instructions
provided to it. The set of instructions is termed as program. Planning of a program involves defining its logic
that is, defining the correct sequence of instructions needed to solve the problem. The process of defining
step- by-step procedure to solve the problem is termed as algorithm. We will try to understand the basics of
algorithm along with the different constructs used in designing the algorithm.
BASICS OF ALGORITHM
The term "algorithm" was originally referred to as any calculation or computation performed by applying set
of rules applied to numbers. It represents a solution to a problem. In our day-to-day life we perform many
activities and we come across different problems too. To complete these activities or to solve these problems
we follow intellectual steps to solve the problem. We follow a method for carrying out some sequence of
events, resulting in accomplishing the task and if we want these tasks to be performed by computer we must
somehow describe it to the computer too.
The algorithm is the sequence of steps to take and get the result. It refers to the logic of a program. It is a step-
by-step description of how to arrive at a solution to a given problem. It is defined as a sequence of instructions
that when executed in the specified sequence, gives the desired result.
Let us write the algorithm for a day-to-day life task or activity as "washing our hands. The step-by-step
process, which is an algorithm, is as follows:
Step I: START the algorithm
Besides algorithm being a finite set of rules that provides a sequence of activities for solving a specific task,
an algorithm must have the following features:
1. Finiteness: An algorithm should provide finite number of steps. It must get terminated or be stopped
after performing finite number of steps and each step must be executed finite number of times.
2. Definiteness: There should not be any ambiguity (uncertainty) in the algorithm. Each step should be
precisely defined.
3. Input: Zero or more finite number of inputs must be provided to an algorithm.
4. Output: An algorithm must have at least one or more output. This is very essential else we will not be
able to find out whether algorithm has provided solution or not.
5. Effectiveness: Each step of an algorithm should be completed with a finite number of steps. It must be
effective to provide finite number of results with finite number of steps.
Thus, in order to qualify as an algorithm, a sequence of instructions must possess the following
characteristics:
BENEFITS OF ALGORITHM
Algorithms help to document the "how to" part for accomplishing a particular task. Once the algorithm is
written it can be used to solve the similar grow of related tasks. Besides this algorithm has following benefits:
1. Better Problem Solving: Algorithm is a systematic process. It involves identifying inputs, variables
and different processes, tasks required for problem solving. This makes problem solving more rational.
2. Improved Efficiency: Algorithms improve the efficiency of solving the problem. It checks whether
all the input variables are considered in problem solving or not. Thus, it makes decision-making more
consistent and efficient.
3. Provides Clarity: Algorithm provides clarity. As algorithm is a step-by-step process of problem
solving, it provides easy access to identification of errors and loopholes from the entire process. Thus,
it provides clarity of the problem to the problem solver.
4. Provides Reusability: Once the algorithm is written it can be reused for a similar type of problem
solving.
Constructs are nothing, but different forms with the help of which an algorithm can be built. Constructs make
an algorithm not only, easy to understand but also to debug and trace the errors. There are three types of
constructs.
1. Sequence
2. Decision
3. Repetition
Sequence
In this type of construct the set of instructions are written sequentially. The instructions are just written one
after another. Figure 2.2 shows the diagrammatic representation of the same.
Action 1
Action 2
Action n
Each action is performed one after the other from top to bottom and left to right as written. The statements are
executed without any condition checking. A sequence construct can be a part of selection and repetition
statements as well.
Step 1: START
Step 8: END
Decision
Comparisons done using relational operators evaluate either true or false. These are also called Boolean
expressions since they return in a Boolean value. A Boolean expression always consists of two alternatives.
Assuming there are two variables a & b containing the values 10 and 11 respectively. Some of the comparison
statements are given as below: Table 2.2 Example of Comparison Operator
The comparison for the given values is done jtsingthe If-End Its construct. It allows the branching of code
with the evaluation of the Bdlean expression. If the Boolean expression returns true, then the set of
statements associated with the true branch is executed. Otherwise the set of statement with the false branch is
executed (if given).
Step 3: I f a%2==0
Step 3: If a > b
Suppose there is a situation where a decision has to be made based on the given condition, to check whether a
given number is even and also a multiple of se\ en In such a scenario, the AND operator can be used. It will
check both the conditions ol even number and multiple of seven.
Assume that salary is between 50,000 and 1,00,000, the tax percentage is 5" else tax percentage is 10%.
Step 4: tax=salary*0.05
Repetition
Sometimes in problem solving we need to execute the same set of instructions repeatedly. In such cases
repetition or Looping constructs are used.
Step I: Start
Step 5: n=n+ I
Step 8: End
Example 11: Algorithm to display the message as per the temperature range.
Temperature greater than or equal to 15 and less than 20: Too Cold
Temperature greater than or equal to 30 and less than 35: Too Hot
Step4: else if temperature >= 15 and temperature <20 then Too Cold
Step 5:
Step6: f=f*counter
Step8: Display f
In this question we are asked to find the sum of 5 numbers. So, we will take two variables - sum and count
and set both of them to zero. The sum variable will store the result while the count variable will keep track of
how many numbers we have read.
To solve this problem we will use the concept of loop. In loop or iterative operation, we execute some steps
repeatedly as long as the given condition is TRUE. In this case we will keep reading the input till we have
read 5 numbers.
So, we first initialize sum and count to zero. Then we will take the input and store it in a variable n. Next we
will add the value stored in n to sum and save the answer in sum.
Then we will increment count by 1 and check if count is less than 5. If this condition is TRUE then we will
take another input. If the condition is FALSE then we will print the value stored in variable sum.
2. Enter n (I/O)
3. Find sum + n and assign it to sum and then increment count by 1 (PROCESS)
5. if YES go to step 2
else
Print sum (I/O)
Flowchart
Example: Print Hello World 10 times
This problem is also solved using the loop concept. We take a variable count and set it to zero. Then we print
"Hello World" and increment count by 1.
Next we check if count is less than 10. If this is TRUE then we again print "Hello World" and increment the
variable count. On the other hand if the condition if FALSE then we will stop.
5. if YES go to step 2
else Stop
Flowchart
Example: Draw a flowchart to log in to facebook account
This problem can be solved in many ways so, we will encourage you to think and draw a flowchart for this
problem using your imagination.
To log in to facebook account we first enter the facbook URL www.facebook.com in our browser like Google
Chrome, Firefox, Safari, Internet Explorer etc. This request is sent to the facebook server and it responds by
sending us the home page of facebook.
Next, we enter our registered Email ID and Password and click the Login button.
Then our login credential is checked. If it is correct, we are show our profile. On the other hand, if the login
credential is wrong then an error occurs and we are prompted to re-enter our Email ID and Password.
Flowchart