[go: up one dir, main page]

0% found this document useful (0 votes)
30 views18 pages

Pseudocode by MR Saem

Uploaded by

Mr Saem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views18 pages

Pseudocode by MR Saem

Uploaded by

Mr Saem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Pseudocode

Pseudocode is an intermediate code between an algorithm (steps explained in


simple English) and a computer program (instructions written in some high-level
language).
• Instructions in a pseudocode doesn’t follow a strict format or syntax as in a
high level language.
• A pseudocode consists of English words like IF…THEN, INPUT, etc as well as
symbols like arithmetic operators (+, –, ×, ÷), assignment ().

Rules for writing pseudocode


1. The statements of a pseudocode can consist of both Commands and symbols.
OUTPUT “Sum of the two numbers is ”, Num_1 + Num_2

2. The commands/keywords are written in UPPERCASE.


INPUT Name
OUTPUT “You Lose”
IF Count < 10

3. The names of the variables/identifiers are written in lowercase with the first
character of the name being a letter and in uppercase.
INPUT Height_of _student
OUTPUT TotalAmount
IF User_turns > 4

4. The names of the subroutines also start with an uppercase.


GetTemperature
GetTime
CalculatePayload

5. In case of a repetition block (loop) or a conditional block, the statements


following the loop or conditional statement are indented by four spaces (the
width of your index finger on a paper.)
IF Age < 18
THEN OUTPUT “Candidate not eligible”

Some common concepts used in pseudocode


Variables
In almost all pseudocodes it will be required that the user enters some data
(numerical values, text, image data, audio data, data taken through sensors etc.) In
order to use these values in our pseudocode, we need to store them in a variable.
Think of a variable as an empty bucket, which you can fill up by placing data.
Rules for naming variables
All variables are given a name and then we reference that variable in any statement
of the pseudocode, using its name. All variables must have a name. the name of the
variable is given according to following rules:

• The name of the variable must begin with an alphabetic character.


• The starting character is written in uppercase and the rest in lowercase.
• You can use numbers as well in your variable name.
• Special characters like _ and . can also be used in variable names.
• Avoid using blank spaces between variable names e.g. Student_Name or
StudentName instead of Student Name.
• Give descriptive names to your variables.
• Character values stored in variable are enclosed in double quotes.
Some common variable name examples are:
Student_Name Age Date_of_birth TotalAmount Counter

Assignment/ Storage
In order to assign a value to a variable we use the following symbol also called the
assignment operator .
Variable_name  Value
Or
Variable_name  Variable_name
For example
Age  20
Day  “Monday”
Tax  Price × 0.25
Squared_value  Value ^ 2
Profit  Sale_price – Purchase_price

Counting
The concept of counting is used when it is required to keep the count of a certain
object or criteria. For example, increasing the customer number by 1 at the
checkout counter of a mall.
Count  Count + 1
Count  Count – 1

Totalling
This concept is used when we are keeping a total of different amounts being
entered. For example, to keep the total sum of profit made on different days of the
week:
Total_amount  Total_amount + profit
Total_bill  Total_bill + Item_price
Before counting or making a total, always set the value of these variables to
0 at the start.

Keywords/ Commands in pseudocode


Getting input and displaying Output on screen
OUTPUT/ PRINT Statement
The OUTPUT statement is used to display the output on the screen. Whatever we
want to display on screen is written after the OUTPUT statement.
OUTPUT “Message” Used when we only want to display a message on screen
OUTPUT Variable_name Used when we want to display the value of variable
OUTPUT “Message”, Variable_name Used to display both the message and the value
1. Ask the user to enter the day of the week.
OUTPUT “Enter day of the week”

2. Display the total amount on screen


OUTPUT Total_amount

Or
OUTPUT “Total amount is: ”, Total_amount
The comma is used as a separator between the message and the variable name.

INPUT/ READ Statement


The INPUT statement is used when we require the user to enter data as input.
INPUT Variable_name
A variable is written after an INPUT statement. The value that the user enters is
stored automatically in the variable.
1. Ask the user to enter the name of the student.
OUTPUT “Enter student name: ”
INPUT Student_name

Example
Write pseudocode for a program that asks for the student name, student roll
number, marks in subjects (Science, English, IT, and Mathematics). The program
than calculates the percentage of the student and displays the result on screen
with the student name and the total marks he, she scored. Assume total marks to
be 400.
We will begin the pseudocode like this:
OUTPUT “Enter name of the student: ”
INPUT Student_name
OUTPUT “Enter student’s roll number: ”
INPUT Student_roll_number
OUTPUT “Enter marks in Science: ”
INPUT Marks_in _Science
OUTPUT “Enter marks in English: ”
INPUT Marks_in _English
OUTPUT “Enter marks in IT ”
INPUT Marks_in _IT
OUTPUT “Enter marks in Mathematics: ”
INPUT Marks_in _Mathematics
Total_marks  400
Obtained_marks  Marks_in_Science + Marks_in_English + Marks_in_IT +
Marks_in_Mathematics
Percentage  (Obtained_marks / Total_marks) * 100
OUTPUT Student_name, “scored”, Obtained_marks, “out of”, Total_marks
OUTPUT Percentage

Practice Questions
1. Write pseudocode that asks for your age and displays the total number of
days you have passed.
2. Write pseudocode that asks the user to enter distance covered by a car and
the time taken. The pseudocode should calculate the average speed and
display it.
3. Write pseudocode to display the following pattern:
@@@@@
@@@@
@@@
@@
@
4. Write pseudocode to calculate the number of seconds in a year.
5. Write pseudocode to merge two words on the display screen.

Making decisions in our pseudocode


IF statement/ clause/ block
Very often you will have to perform some conditional tasks in your program like
comparison (input a is greater than input b), or checks. In such cases you can use
either the IF statement or CASE…OF statement.
The IF statement has different flavors. Depending upon the program logic, we can
use one or more of the flavors of the IF statement in our program to build
conditional logic.

• IF…THEN statement
• IF…THEN…ELSE statement
• Nested IF structure

IF…THEN Statement
IF condition THEN statement(s)
ENDIF
Or
IF condition
THEN statement(s)
ENDIF
Or
IF condition
THEN
IF condition
THEN statement(s)
ENDIF
ENDIF
You can use any of the above syntax.
1. To check if number of students are competed.
IF Number_of_students < 40 THEN OUTPUT “Seats available.”
ENDIF
2. To check if name is a certain name or not.
IF Name <> “Martha”
THEN
OUTPUT “Identity Mismatch”
INPUT Name
ENDIF

3. To check if person is above or 20 and male.


IF Age >= 20
THEN
IF Gender = “M”
THEN OUTPUT “Welcome to Boys hostel.”
ENDIF
ENDIF
We can also perform the above conditional check using logical AND gate:
IF Age >= 20 AND Gender = “M”
THEN OUTPUT “Welcome to Boys hostel.”
ENDIF

In all the examples above, the statements with THEN are executed only if the
condition mentioned with IF statement turns out to be True.
Limitation: In case if the condition is False, we see no alternate action taking
place. The screen will be blank in above cases.

IF…THEN…ELSE Statement
The IF THEN ELSE statement is used when we to perform alternate actions
regardless of whether the IF statement evaluates to true or false. If the condition
specified with IF is true THEN statement is executed, if it is false, ELSE statement
is executed.
IF condition THEN statement(s) ELSE statement(s)
ENDIF
Or
IF condition
THEN statement(s)
ELSE statement(s)
ENDIF
Or
IF condition
THEN
IF condition
THEN statement(s)
ELSE statement(s)
ENDIF
ELSE
statement(s)
ENDIF
Depending upon the program, available space on page and time You can use any of
the above syntax.
Example
In a factory, employees have to work 50 hours a week to get a wage of 10,000$. The
overtime rate is 20$ per hour. Write a pseudocode code that asks the employee to
enter number of hours worked in a week and checks if the employee gets overtime
bonus or reduction in payment for working a smaller number of hours than 50. The
reduction is 150$ per hour.
Base_wage  30000
Over_time_rate  20
Penalty_rate  150
OUTPUT “Enter number of hours worked: ”
INPUT Hours_worked
IF Hours_worked >= 50
THEN
Over_time_bonus  (Hours_worked - 50) * Over_time_rate
Total_wage  Base_wage + Over_time_bonus
OUTPUT “Total wage is: ”, Total_wage
ELSE
Penalty  (50 – Hours_worked) * Penalty_rate
Total_wage  Base_wage – Penalty
OUTPUT “Total wage is: ”, Total_wage
ENDIF

Nested IF statement
A nested structure means a conditional statement within another conditional
statement. A nested IF statement can have the following structure:
IF condition
THEN
IF condition
THEN
IF condition
THEN statement(s)
ELSE statement(s)
ENDIF
ENDIF
ENDIF
Example
Write pseudocode to check if a year is a leap year or not.
OUTPUT “Enter a year: ”
INPUT Year
IF Year % 4 = 0
THEN
IF Year % 100 = 0
THEN
IF Year % 400 = 0
THEN OUTPUT “It is leap year.”
ELSE OUTPUT “It is not a leap year”
ENDIF
ELSE OUTPUT “It is a leap year”
ENDIF
ELSE OUTPUT “It is not a leap year.”
ENDIF

CASE…OF…OTHERWISE…ENDCASE Statement
This statement is used when we have multiple options to select from and one of the
options needs to be selected.
CASE variable OF
Value1: statement
Value2: statement
Value3: statement
.
.
.
ValueN: statement
OTHERWISE statement
ENDCASE
In the above syntax the CASE statement is used to check the variable value. The
variable holds a value specified in the program or entered by the user. The value of
that variable is matched with the values below (Value1, Value2, Value3 up to N
number of values). Each value has statement(s) mentioned with it. In case of
matching value, its statements are executed.
In case if no value matches with the variable’s value then the statements
mentioned with OTHERWISE are executed and at the end the case structure ends
with an ENDCASE statement.
Example
In a game in order to set reward scores for treasure chests.
OUTPUT “Enter which treasure chest to open (1, 2, 3, 4, 5, 6): ”
INPUT Chest_number
Choice Chest_number OF
1: Score  Score + 50
2: Score  Score + 34
3: Score  Score + 72
4: Score  Score + 152
5: Score  Score + 10
6: Score  Score + 28
OTHERWISE OUTPUT “You picked the wrong chest.”
ENDCASE

Repeating processes in our pseudocode


It is often required in programs to repeat a set of statements up to a number of
times. For example, you may want the program to keep checking when the player
life drops to zero and until that happens, keep repeating all the game code. In
programs or pseudocodes, the statements that let us repeat a group of statements
again and again until a specific condition becomes false, are known as loops.
There are three types of loop structures we can use in our pseudocodes:
1. FOR…TO…NEXT loop
2. REPEAT…UNTIL loop
3. WHILE…DO…ENDWHILE loop
Each loop is used for a different purpose but they all are used to repeat statements.

FOR…TO…NEXT statement
When it is known in advance that how many times, we need to repeat the
statements to get our final output, FOR…TO…NEXT statement fits the job.
FOR variable  x TO y STEP z
Statement 1
Statement 2
Statement 3


Statement n
NEXT
In the above syntax a variable is used with FOR which is set to a starting limit x
(for example 1 or 0) and an ending limit y (for example 10, 1000, 237236178 etc.).
The loop will repeat the statements inside it based on the difference between y and
x. X and Y should be integers (whole numbers). The variable used with FOR is also
called the loop control variable.
The NEXT keyword is used to repeat the next cycle of the loop also known as an
iteration.
Example
FOR Count  1 TO 10
OUTPUT “This sentence will be repeated 10 times.”
NEXT

OUTPUT
OUTPUT
This sentence will be repeated 10 times.
1
This sentence will be repeated 10 times.
2
This sentence will be repeated 10 times.
3
This sentence will be repeated 10 times.
4
This sentence will be repeated 10 times.
5
This sentence will be repeated 10 times.
6
This sentence will be repeated 10 times.
7
This sentence will be repeated 10 times.
8
This sentence will be repeated 10 times.
9
This sentence will be repeated 10 times.
10

Example
To display the variable value as output.
FOR Count  1 TO 10
OUTPUT Count
NEXT
We can use the STEP command to set a step of z (gap). OUTPUT
Example 2
FOR EVEN  2 TO 20 STEP 2 4
OUTPUT EVEN 6
NEXT 8
Once the loop is completed, the statements after the loop are 10
executed.
12
The FOR…TO…NEXT is the easiest loop structure to set up. We
can also have a nested structure of FOR…TO…NEXT loop. In that 14
case the inner loop will run for its entire limit for a single value of
16
the outer loop.
18
FOR loop is also handy when assigning values to the index of an
array as we will see later. 20
REPEAT…UNTIL statement
FOR loop works best when you know how many times to repeat the statements, but
in case where it is not known how many times the statements will be executed until
the output is achieved, REPEAT…UNTIL or WHILE…DO…ENDWHILE are used.

REPEAT
Statement 1
Statement 2
Statement 3


Statement n
UNTIL criteria matches
Example
Suppose you want the user to guess the number you have set as the lucky number
between 0 and 100. In our case let’s assume that the lucky number is 95 and the
user needs to guess it. In such a case we are not sure that after how many tries the
user will guess the number? It can be after 10 tries, 20 tries or may be even the
first attempt.
In such a case we need to set a flag condition (a criteria) that if the number user
enters is matched with the set number than terminate the loop and move on to
other statements, otherwise keep on asking him for the guess.
The REPEAT…UNTIL statement can be used here to repeat the action of asking the
user to input the lucky number until the number is picked. The program will keep
on prompting the user to enter the number until the number entered matches the
set lucky number.
Lucky_number = 95
REPEAT
OUTPUT “Enter guess number: ”
INPUT Number
UNTIL Number = Lucky_number
Example
REPEAT
GAMEPLAY_ON
UNTIL Player_hp < 1
Statement(s) after the loop
Until the criteria is met, REPEAT will keep on repeating the statements mentioned
in its block. When the criteria is matched, the loop terminates and the statements
after the loop are executed.

WHILE…DO…ENDWHILE statement
In case of REPEAT…UNTIL loop, the statements in the loop are executed first and
then it is checked if the criteria is met or not. In WHILE…DO…ENDWHILE loop a
condition is first checked and as long as the condition is true, the statements
inside the loop will be executed.
WHILE condition is true
DO
Statement 1
Statement 2
Statement 3


Statement n
ENDWHILE
The statements inside the loop will be executed only if the condition after the
WHILE loop holds to be true. In case if it is false, the loop will not enter its block
and just get terminated.
Example
To check if a number is prime number.
OUTPUT “Enter number: ”
INPUT Num
N  2
Flag  False //a bool type variable
WHILE N < Num
DO
IF Num % N = 0
THEN
Flag  True
N  Num //To stop the loop. We can also use “BREAK” keyword.
ELSE
N  N + 1
ENDIF
ENDWHILE
IF Check = False
THEN OUTPUT “Number is Prime.”
ELSE OUTPUT “Number is not Prime.”
ENDIF

Introducing array structure in our pseudocode


• An array is a collection of variables given a single name.
• All values in an array are of the same data type the array was initialized as.
• The elements stored in array have special addresses assigned to them. These
are called Locations/indices/addresses/subscripts of the stored values.

A0 A1 A2 A3 A4 A5 A6
𝐴(6) = 5 10 15 20 25 30 null

Notice that the array has 6 elements {5, 10, 15, 20, 25, 30} and each element has
the address A0, A1, A2, A3, A4, A5 assigned to it.
Note: There is a difference between a list and an array structure.
Two common types of array that are encountered are:
1-Dimensional array
2-Dimensional array

Initializing a 1-Dimensional array


To use/initialize an array in our pseudocode we need to first define the array and
its data type.
Note: This is not necessary as the convention of defining an array varies from
teacher to teacher. (Remember a pseudocode has no rules except for the ones you
define.)
Array_name[size of array] AS data type of array
Example
1. To define the array student marks:
Student_marks[20] AS Integer

2. To define an array for temperature record over a week:


Temperature[7] AS Float

We can also use a variable for the size of array.


OUTPUT “Enter number of cards: ”
INPUT Num_of_cards
Cards[Num_of_cards] AS String

Assigning values to array


Method 1
An array is empty at the start, there are no values in the array. We can enter data
manually into an array (also known as populating the array) using the following
syntax:
Array_name[location_in_array]  value
Example
Student_marks[0]  119
Student_marks[1]  110
Student_marks[2]  138
Student_marks[3]  77
Student_marks[4]  90
Student_marks[5]  105


Student_marks[16]  79
Student_marks[17]  83
Student_marks[18]  120
Student_marks[19]  96
It is important here to notice the following things here:
• We started populating the array from the location 0 in the array.
• When assignment is used with an array here in pseudocode, the number in
the square brackets [ ] points to the location in the array where the assigned
value will be stored and not the size of the array.
• We stopped populating our array at the location [19], even though we
initialized the array with a size of 20. This is good practice as it will also help
in converting pseudocode arrays to actual programming arrays.
• You can also start your array from location 1 instead of zero. In that case the
size of the array will be taken as size + 1.

Method 2
Another way to populate an array is through loops, and the easiest to use with an
array is the FOR loop.
Example
Write pseudocode that finds the average of given list of marks of students:

Sum = 0
OUTPUT “Enter number of students: ”
INPUT Number_of_students
Student_marks[Number_of_students + 1] AS Integer
FOR Count  1 TO Number_of_students
OUTPUT “Enter marks of student number ”, Count
INPUT Student_marks[Count]
Sum  Sum + Student_marks[Count]
NEXT
OUTPUT “Average marks are: ”, Sum / Number_of_stduents

Example
Write pseudocode that stores five names in an array and prints them in reverse
order:
Names[6] AS String
FOR Count  1 TO 5
OUTPUT “Enter name: ”
INPUT Names[Count]
NEXT
FOR Count  5 TO 1 STEP -1
OUTPUT Names[Count]
NEXT
Initializing a 2-Dimensional array
A 2-Dimensional array is same as a table with rows and columns. To initialize a 2-
Dimensional array we use the following syntax:
Array_name[number of rows] [number of columns] AS data type of array
Example
To define a matrix with 4 rows and 3 columns:
Game_grid[4][3] AS Integer
You can conceptualize the above array as follow

Column 0 Column 1 Column 2


Row 0 Location [0][0] Location [0][1] Location [0][2]
Row 1 Location [1][0] Location [1][1] Location [1][2]
Row 2 Location [2][0] Location [2][1] Location [2][2]
Row 3 Location [3][0] Location [3][1] Location [3][2]

• Since we started our count from 0 therefore max row# is 3 and max column#
is 2.
• The above array can store 12 entries in it. To get how many entries the array
can store use the formula 𝑟𝑜𝑤𝑠 × 𝑐𝑜𝑙𝑢𝑚𝑛𝑠.

Assigning values to 2-Dimensional array


We can use the same methods we used to assign values to a 1-Dimensional array.
Example
Matrix_values[0][0]  5
Matrix_values[0][1]  3
Matrix_values[1][0]  8
Matrix_values[1][1]  2
5 3
8 2
Or we can also use nested loop structure to assign values to the array.
Minesweeper[10][10] AS Integer
FOR Rows  0 TO 9
FOR Columns  0 TO 9
Minesweeper[Rows][Columns]  0
NEXT Columns
NEXT Rows
Using subroutines in our pseudocode
A subroutine is a set of instructions formed as a separate block of code from the
main program and given a name. The name of the subroutine is used as a
statement to call the subroutine code anywhere in your program without repeating
the code again and again.
There are two types of subroutines:
Procedures – subroutines which when called do their work and that is all what
they do.
Functions – subroutines which when called do their work and also return a value
to the main program. This returned value can be a number, string, a flag signal
(bool) etc.
Both procedures and functions can use input parameters on which they can
operate on.
To use a procedure in our code we can use the following syntax:
PROCEDURE Procedure_name(Parameters if any)
Statements

ENDPROCEDURE
To use a procedure in our program we can use the CALL statement.
CALL Procedure_name
Example
PROCEDURE Print_stars( )
OUTPUT “********************” Procedure

ENDPROCEDURE
OUTPUT “How many lines to print? ”
INPUT Num_lines
FOR Count  1 TO Num_lines Main Program

CALL Print_stars
NEXT
To use a function in our code we can use the following syntax:
FUNCTION Function_name(Parameters if any) RETURN Data_Type
Statements

ENDFUNCTION
The return data_type is the type of value that will be returned by the function to
the main program.
Function Definition
Example
FUNCTION Sum_of_series(Number : Integer) RETURN : Integer
Total  (Number * (Number + 1)) / 2
RETURN Total
ENDFUNCTION
OUTPUT “Up to how many numbers you want the sum of starting from 1: ”
INPUT Num
Sum  Sum_of_series(Num)
OUTPUT “Sum of the series is: ”, Sum
In the above example, we have a passed a parameter “Number” to the function
which basically means that when we are going to call the function we need to
supply the value of the parameter.
The value can be passed has a hardcoded input like Sum  Sum_of_series(80) or
it can be a variable as in the above case. The important thing is that which ever
value you passed to the function must match the data type of the parameter as
stated in the function definition.
When the function is called in the program,

• We don’t have to use the CALL statement to call the function. We can just
write the name of the function to call it.
• We also need a variable matching the return type of the RETURN statement
in function definition. This variable will store the returned value of the
function.

You might also like