Você está na página 1de 23

PSEUDOCODES

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 all the above operations, pseudocode can be written.

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

So the result of computing 5*2 is assigned to the variable a.

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

Table 1.1 Mathematical Operators used in Pseudocode


Operator Function
() Parenthesis
^ or ^^ Exponentiation
- Negation
*,/ Multiplication, Division
% Modulus or Remainder
+,- Addition, Subtraction
= Assignment

RULES FOR WRITING PSEUDOCODES

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:

It should be able to convey the intention of the program.


The statements should be simple and unambiguous.
Since it is a balance between code and informal natural language, it is necessary to follow the rules
of both.
Precise and comprehensible English sentences should be written instead of full sentences.
Comments should be included where useful and required for better understanding of the code.
Variable names should be written as mnemonics, so that it is easy to remember. They are also
called identifiers. An identifier should not contain spaces.
Although the syntax is not important, it is better to use conventional programming statements like
begin/end.
Programming shorthand should be used instead of using equivalent English sentences for the same,
e.g., a group of statements can be repeated using while statement.
For better readability, use one statement per line and should represent one operation to be
performed.
Keywords should he written in capital letters, e.g., READ, GET, etc.
If hierarchical statements are used, then indent the statements.
The code should be as far as possible written in a language-independent form.
Variable names should be unique to a program.
Scope terminators like START and END should be used at the start and end of the pseudocode.

WRITING DIFFERENT STATEMENTS IN PSEUDOCODE

The steps of writing the sequence, selection and repetition statements in pseudocodes are discussed below.

Sequence Statements in Pseudocode

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,

Read principal, rate, time


It means the values entered by the keyboard go into the three variables: The first value entered goes into
principal, the second value goes into rate and the third value goes into time.

The statement

Print si

prints the value contained in the variable si to the output screen.

Selection Statements in Pseudocode

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.

Table 1.2 Relational Operators to make Comparisons

Symbol Function performed


< strictly less than
<= less than or equal to
> strictly greater than
>= greater than or equal to
== equal to
!= not equal to

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:

Comparison Expression Result


X+1==y True
y-1==x True
X!=y True
X==y False

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

Print "Number is even"

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

Print "Number is even"

else

Print "Number is odd"

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.

Table 1.3 Logical Operators used in a Boolean Expression

Logical Operator Function


AND Returns true when both the conditions
(Boolean expressions) are true
OR Returns true if either condition (Boolean
expression) is true
NOT Returns true if the condition (Boolean
expression) is false

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

If number %2==0 AND number %7==0 then

Print " Even and multiple of seven"

End if

In the above example, two Boolean expressions are given

Number %2==0

And

Number %7==0

Now when both the expressions are true with the true branch is executed.

ADVANTAGES AND DISADVANTAGES OF PSEUDOCODE

After discussing the concepts of pseudocodes, let us talk about their advantages and disadvantages.
Advantages

It provides the programmer with a detailed template of the actual code.


A dry run of the pseudocode or debugging helps the programmer to find errors easily and is less costly
as compared to finding errors in the computer program.
If the pseudocode is accepted, it is rewritten using the syntax and conventions of a programming
language.
A pseudocode written once for a particular problem can be converted easily to any programming
language.
It is easy to modify.
It can be easily written using any editor.
Disadvantages

It is not visual.
Since there is no standard, pseudocode written by two persons will differ.

What is the difference between Algorithm and Pseudocode?

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.

Read num1 , num2


Set multi to num1*num2
Write multi

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.

Write "Please enter a number"


Read colornum
If (colornum >0 and colornum <= 10)
Write blue
else If (colornum >0 and colornum <= 10)
Write blue
else If (colornum >0 and colornum <= 10)
Write blue
else
Write "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

Step 2: Turn on water.

Step 3: Dispense soap.

Step 4: Wash hands till clean.

Step 5: Rinse soap off.

Step 6: Turn off water

Step 7: Dry hands.

Step 8: END 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:

1. Each instruction should be precise and unambiguous.


2. Each instruction should be executed in a finite time.
3. One or more instructions should not be repeated infinitely. This ensures that the algorithm will
ultimately terminate.
4. After executing the instructions (when the algorithm terminates) the desired results are obtained.

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.

Let us see some more examples of algorithm.

Example 1: Algorithm to display the addition of three numbers.

Step 1: START the algorithm.

Step 2: READ the first number.

Step 3: READ the second number.

Step 4: READ the third number.

Step 5: Add the three numbers.

Step 6: DISPLAY the result.

Step 7: END the algorithm.

Example2: Algorithm to display the cube of a number.

Step 1: START the algorithm.

Step 2: READ the number.

Step 3: Calculate cube of the number.

Step 4: DISPLAY the result.

Step 5: END the algorithm.

CONSTRUCTS FOR DEVELOPING ALGORITHM

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

Fig. 2.2: Sequence Construct

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.

Example 3: Algorithm to display the average of three numbers.

Step 1: START

Step 2: READ the first number.

Step 3: READ the second number.

Step 4: READ the third number.

Step 5: Add the three numbers.

Step 6: Divide the addition of three numbers by 3.

Step 7: DISPLAY the result.

Step 8: END

Decision

Table 2.1 Comparison Operators

Symbol Function performed


< strictly less than
<= less than or equal to
> strictly greater than
>= greater than or equal to
== equal to
!= not equal to

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

Comparison Expression Result a+ I =--- b true a>'b false ... a ! = b true

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

Example 6: Algorithm to check whether number is even or odd.

Step I: Start the algorithm.

Step 2: Read number a.

Step 3: I f a%2==0

Step 4: Display 'a' is even

Step 5: Else display a is odd.

Step 6: End the algorithm.

Example 7: Algorithm to find greatest of two numbers.

Step I: Start the algorithm.

Step 2: Declare two variables a & b.

Step 3: If a > b

Step 4: Display a is largest.

Step 5: EIse display b is largest.

Step 6: Display the result.

Step 7: End the algorithm.


Comparison expressions or Boolean expressions can be made more complex with the use of logical operators.
Logical operators are used to control program flow. The different logical operators that are used in a Boolean
expression are as follows:

Table 2.3: Logical Operators

Logical Operator Function


AND Returns true when both the conditions
(Boolean expressions) are true
OR Returns true if either condition (Boolean
expression) is true
NOT Returns true if the condition (Boolean
expression) is false

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.

Example 9: Algorithm to calculate the tax for an employee.

Assume that salary is between 50,000 and 1,00,000, the tax percentage is 5" else tax percentage is 10%.

Step I: Start the algorithm.

Step 2: Read salary

Step 3: If salary >50,000 and salary <I ,00 000

Step 4: tax=salary*0.05

Step 5: Else tax= salary*0.10

Step 6: Display the tax value.

Step 7: End the algorithm.

Repetition

Sometimes in problem solving we need to execute the same set of instructions repeatedly. In such cases
repetition or Looping constructs are used.

Example 10: Algorithm to print 1 to 100 numbers,

Step I: Start

Step 2: Declare variable n.


Step 3: Initialize variables n=1

Step 4: Print value of n

Step 5: n=n+ I

Step 6: lf n==101 go to step 8

Step 7: Else go to step 4.

Step 8: End

Example 11: Algorithm to display the message as per the temperature range.

Temperature less than 15: Too Too Cold

Temperature greater than or equal to 15 and less than 20: Too Cold

Temperature greater than or equal to 20 and less than 25: Cold

Temperature greater than or equal to 25 and less than 30: Normal

Temperature greater than or equal to 30 and less than 35: Too Hot

Temperature greater than or equal to 35: Too Too Hot

Step1: START the algorithm

Step2: input temperature

Step 3: if temperature <15 then Too too cold

Step4: else if temperature >= 15 and temperature <20 then Too Cold

Step 5:

Example: Write an algorithm to find out the factorial of a number.

Step1: START the algorithm

Step2: Read variables n, f, counter

Step3: Initialize counter=1, f=1


Step4: Input the value n from user

Step5: Repeat step6 till counter>n

Step6: f=f*counter

Step7: Increment the Counter by 1

Step8: Display f

Step9: END the Algorithm


Example: Find the sum of 5 numbers

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.

i.e., sum = sum + n

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.

Algorithm (in simple English)

1. Initialize sum = 0 and count = 0 (PROCESS)

2. Enter n (I/O)

3. Find sum + n and assign it to sum and then increment count by 1 (PROCESS)

4. Is count < 5 (DECISION)

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.

i.e., count = count + 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.

Algorithm (in simple English)

1. Initialize count = 0 (PROCESS)

2. Print Hello World (I/O)

3. Increment count by 1 (PROCESS)

4. Is count < 10 (DECISION)

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.

Algorithm (in simple English)


1. Enter www.facebook.com in your browser. (I/O)

2. facebook Home page loads (PROCESS)

3. Enter your Email ID and Password (I/O)

4. Is Email ID and Password Valid (DECISION)


if NO then
Log in error (PROCESS)
go to step 3
else
Display facebook Account (I/O)
Stop

Flowchart

Você também pode gostar