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

Pseudocode Operators

csss

Uploaded by

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

Pseudocode Operators

csss

Uploaded by

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

Handout

CHAPTER 7 :Pseudocode
COMPUTER SCIENCE-OL3
NAME: _________________ DATE: _______________

Pseudocode Operators
Math Operation Syntax Example Answer
Multiplication * 5*2 10
Division / 10 / 2 5
Addition + 6+3 9
Subtraction - 7 + 12 19
MOD Remainder 7 MOD 5 2
Division
DIV Integer Division 7 MOD 5 1
Comparison Operation Syntax

Less Than <

Less Than Equals To <=

Greater Than >

Greater Than Equals To >=

Equals To =

Not Equals To <>

Logic Operations :
 AND
 OR
 NOT

Variable :
The value of a variable can change throughout the execution of a program.

Variable Data Types


Data Type Explanation Example

Integer Whole Numbers 23


Real Decimal Numbers 23.67
Character/ One singular character “N”
Char
String Alpha-numeric values “Nerd Cafe Study Spot “
Boolean Comparison TRUE
Date Date 22/12/2024

Variable Data Type Declaration:


Variable declaration is done at the start of a program. For example :
DECLARE num : INTEGER
DECLARE name: STRING
DECLARE answer: BOOLEAN

Constant:
Its value does not change throughout the execution of a program, and is assigned by the
programmer.

Constant Declaration:
CONSTANT pi = 3.14 CONSTANT price = 25

INPUT and OUTPUTS:


OUTPUT Statements:
 OUTPUT “The price is:”, price
 price = 25
 OUTPUT “My name is Ali.”
INPUT Statements:
 INPUT NUM
 INPUT name
Conditional Statements:
1. IF…THEN…ELSE…END IF For an IF condition, the THEN path is followed if the
condition is true and the ELSE path is followed if the condition is false. There may or
may not be an ELSE path. The end of the statement is shown by ENDIF. There are
different ways that an IF condition can be set up
Examples :
- Use of a Boolean variable :
IF Condition A
THEN
OUTPUT “true”
ELSE
OUTPUT “false”
END IF
- Making Comparison:

IF Condition A > Condition B


THEN
OUTPUT “...”
ELSE
OUTPUT “…”
END IF
- Nested IF:

IF Condition A > Condition B AND Condition C


THEN
OUTPUT “…”
ELSE
IF Condition B > Condition A AND Condition C
THEN
OUTPUT “…”
ELSE
OUTPUT “…”
END IF
END IF

Q. Write pseudocode for a program that inputs a number from the user and print whether
the number is positive, negative or a zero.

Solution :
OUTPUT “Enter a number:”
INPUT num
IF num > 0
THEN OUTPUT “Positive”
ELSE
IF num < 0
THEN OUTPUT “Negative”
ELSE
OUTPUT “Zero”
ENDIF
ENDIF
2. CASE OF…OTHERWISE….END CASE
For a CASE statement, the value of the variable decides the path to be taken. Several values
are usually specified. OTHERWISE is the path taken for all other values. The end of the
statement is shown by ENDCASE.
CASE Of Choice
1: Condition A
2: Condition B
3: Condition C
OTHERWISE OUTPUT “…”
END CASE

Q. Write pseudocode for a program that inputs a number from the user and print whether
the number is positive, negative or a zero.

Solution:

OUTPUT “Enter a number:”


INPUT num
CASE num OF
0 : OUTPUT “Positive”
< 0 : OUTPUT “Negative”
OTHERWISE OUTPUT “Zero”
ENDCASE
The pseudocode for iteration
1. FOR..TO..NEXT. (count-control loop)
 iterates a specific number of times
 Uses a loop variable with a specified range
FOR Counter <- 1 to 10
OUTPUT “…”
NEXT Counter

1. WHILE…DO…ENDWHILE (per-condition loop)


 repeats as long as a condition is true
 Condition is checked before entering the loop

Counter <- 0
WHILE Counter < 10 DO
OUTPUT “…”
Counter <- Counter + 1
ENDWHILE
1. REPEAT…UNTIL (post-condition loop)
 repeats until a condition becomes true
 Condition is checked before and after each iteration
Counter <- 0
REPEAT
OUTPUT “…”
Counter <- Counter + 1
UNTIL Counter > 9

Q. Write a program to input numbers from the user and print them. The program stops
when the user enters 0 as an input.

Solution:
REPEAT
OUTPUT “Enter a number or 0 to stop:”
INPUT num
OUTPUT “You entered:”, num
UNTIL num = 0
● Totalling

Total <- 0
FOR Counter <- 1 TO 10
INPUT X
Total <- Total + X
NEXT Counter
OUTPUT Total
● Counting
Copy
Count <- 0
FOR Counter <- 1 TO 10
IF Condition A
THEN
Count <- Count + 1
END IF
NEXT Counter
OUTPUT Count
● Maximum (In maximum, store the minimum value)
Maximum <- 0
FOR Counter <- 1 TO 10
INPUT X
IF X > Maximum
THEN
Maximum <- X
END IF
NEXT Counter
OUTPUT Maximum
● Minimum (In minimum, store the maximum value)

Minimum <- 0
FOR Counter <- 1 TO 10
INPUT X
IF X < Minimum
THEN
Minimum <- X
END IF
NEXT Counter
OUTPUT Minimum
● Linear Search
 For 1D Array :
DECLARE Index: INTEGER
FOR Index <- 1 TO 500
IF Names[Index] = "Nerd"
THEN
OUTPUT index
ENDIF
ENDFOR
 For 2D Array:
DECLARE Repeat: INTEGER
DECLARE row-index: INTEGER
DECLARE column-index: INTEGER

Repeat = 0
FOR row-index <- 1 TO 500
FOR column-index <- 1 TO 30
IF Searchbox[row-index,column-index] = "Empty"
THEN
Repeat = Repeat + 1
ENDIF
ENDFOR
ENDFOR
OUTPUT Repeat

 Bubble Sort

Boundary = 99
REPEAT
NoSwaps = TRUE
FOR j = 1 to Boundary
IF studentID[j] > studentID[j+1]
THEN
TEMP = studentIG[j]
studentID[j] = studentID[j+1]
studentID[j+1] = TEMP
NoSwaps = FALSE
ENDIF
ENDFOR
Boundary = Boundary - 1
UNTIL NoSwaps = TRUE
Validation
The automated checking by a program that the data is reasonable before it is entered

1. Range Check: Check that the value of a number is between an upper value and a lower
value Example: To check that X is between 0 to 100
REPEAT
INPUT X
IF X < 0 OR X > 100
THEN
OUTPUT “value is out of range, please re-enter”
END IF
UNTIL X >= 0 OR X <= 0
2. Length Check: Check that the data entered contains an exact number of characters or
a reasonable number of characters Example: To check that X has between 1 to 10
characters
REPEAT
INPUT X
IF LENGTH(X) < 1 OR LENGTH(X) > 10
THEN
OUTPUT “value too short or too long, please re-enter”
END IF
UNTIL LENGTH(X) >= 1 OR LENGTH(X) <= 10

3. Type Check: Check, whether the data entered, is of a specific data type Example: To
check that X is an integer
Copy
REPEAT
INPUT X
IF X <> DIV(X,1)
THEN
OUTPUT “Please enter a whole number”
END IF
UNTIL X = DIV(X,1)
4. Presence Check: Check to ensure some data has been entered and the value has not
been left blank Example:
REPEAT
INPUT X
IF X = “”
THEN
OUTPUT “Please enter a value”
END IF
UNTIL X <> “”
5. Format Check: Check that the characters entered conform to a predefined pattern
Example: To check that X is in format XXX9999
INPUT X
IF LENGTH(X) = 7
THEN
IF IS_APLHABETIC(SUBSTRING(X,1,3)) AND
IS_NUMERIC(SUBSTRING(X,4,7))
THEN
OUTPUT “valid”
ELSE
OUTPUT “invalid format, please re-enter”
END IF
ELSE
OUTPUT “Please enter a 7-digit value”
END IF

Procedures and Functions:


When writing an algorithm, there are often similar tasks to perform that use the same groups of
statements. Instead of repeating these statements and writing new code whenever required,
many programming languages use subroutines, also known as named procedures or functions.
These are defined once and can be called many times within a program.
A procedure is a set of programming statements grouped under a single name
that can be called to perform a task at any point in a program.
A function is a set of programming statements grouped under a single name that can be called
to perform a task at any point in a program. In contrast to a procedure, a function will return a
value to the main program.
Parameters are the variables that store the values of the arguments passed to a procedure or
function. Some but not all procedures and functions will have parameters.

Procedures:
 Syntax of procedure without parameters:
PROCEDURE ProcedureName
[commands]
END PROCEDURE
CALL ProcudureName
 Here is an example of a procedure without parameters in pseudocode:
PROCEDURE Stars
PRINT “*******”
ENDPROCEDURE
 The procedure can be called in the main part of the program as many times as it is
required in the following way:

CALL Stars
 Syntax of procedure with parameters:
PROCEDURE ProcedureName (ParameterName : ParameterDatatype)
[Commands]
ENDPROCEDURE
CALL ProecdureName (ParameterValue)
We can add parameters to a procedure:
PROCEDURE Stars (Number: INTEGER) //parameter with data type
FOR I <- 1 TO Number
OUTPUT “*”
NEXT I
ENDPROCEDURE
 The procedure with parameters is called like this: (assuming we want to print 7
stars)
CALL Stars(7)

Functions:
 Syntax of function with parameters
FUNCTION FunctionName (ParameterName : ParameterDatatype) RETURNS
DataTypeOfValueReturned
[Commands]
RETURN ValueToBeReturned
ENDFUNCTION
 Here is an example of a function to convert a temperature from Fahrenheit to
celsius:
FUNCTION Celsius (Temperature: REAL) RETURNS REAL
RETURN (Temperature - 32)/1.8
END FUNCTION





 To call a function in the main program we can assign the return value to a variable
:
Temp <- Celsius(Temp)
When procedures and functions are defined, the first statement in the definition is a header,
which contains: » the name of the procedure or function » any parameters passed to the
procedure or function, and their data type » the data type of the return value for a function.

Global and Local Variables:


A global variable can be used by any part of a program - its scope covers the whole program. A
local variable can only be used by the part of the program it has been declared in - its scope is
restricted to that part of the program.
Library Routines
 Programming language development systems often provide library routines that can be
readily incorporated into programs.
 Library routines are pre-tested and ready for use, making programming tasks easier.
 Integrated Development Environments (IDEs) typically include a standard library of
functions and procedures.
 Standard library routines perform various tasks, including string handling. Library
Routines Required for IGCSE- ● MOD – returns the remainder of a division ● DIV –
returns the quotient (i.e. the whole number part) of a division ● ROUND – returns a value
rounded to a given number of decimal places ● RANDOM – returns a random number.

Examples:
● Value1 <--- MOD(10,3) returns the remainder of 10 divided by 3
● Value2 <---- DIV(10,3) returns the quotient of 10 divided by 3
● Value3 <--- ROUND(6.97354, 2) returns the value rounded to 2 decimal places ● Value4 <---
RANDOM() returns a random number between 0 and 1 inclusive
An array is a data structure containing several elements of the same data type; these elements
can be accessed using the same identifier name. The position of each element in an array is
identified using the array’s index.

● One-dimensional arrays - can be referred to as a list


Declaring a 1D Array:
DECLARE MyArray[1:50] OF INTEGER
● Two-dimensional arrays - can be referred to as a table
Declaring a 2D Array:
DECLARE VariableName : ARRAY[1:NumberOfRows, 1:NumberOfColumns] OF DataTya
Note: When using a 2-D array with loop structures, there needs to be two loops, one for each
index.
Sample Array Questions -
1. Write a pseudocode to calculate the sum of each row
DECLARE X : ARRAY[1:10 , 1:5]
FOR I <- 1 TO 10
SUM <- 0
FOR J <- 1 TO 5
SUM <- SUM + X [I][J]
NEXT J
OUTPUT SUM
NEXT I

2. Write a pseudocode to calculate the sum of each column


DECLARE X : ARRAY[1:10 , 1:]
FOR J <- 1 TO 5
SUM <- 0
FOR I <- 1 TO 10
SUM <- SUM + X [I][J]
NEXT I
OUTPUT SUM
NEXT J

File Handling
Purpose of storing data in a file Computer programs store data that will be required again in a
file. While any data stored in RAM will be lost when the computer is switched off when data is
saved to a file it is stored permanently. Data stored in a file can thus be accessed by the same
program at a later date or accessed by another program. Data stored in a file can also be sent
to be used on another computer(s). Files can be opened in the following modes
1. Read Read data from the file
Syntax:
OPEN <file name> FOR <file mode>
READ <variable>
CLOSEFILE <file name>

Example:
FOR I <- 1 TO 10
OPENFILE “file.txt” FOR READ
X <- file.txt
READ X
NEXT I
CLOSE FILE “file.txt”
NOTE: ‘CLOSEFILE’ statement using FOR..TO… NEXT Loop can only be used when we know
the number of elements. If the number of elements is unknown we use the statement ‘EOF’
which stands for End Of File using a REPEAT…UNTIL Loop.

Example:
REPEAT
OPENFILE “file.txt” FOR READ
X <- file.txt
READ X
UNTIL EOF “file.txt”
2. Write Writes data to the file, any existing data stored in the file will be overwritten.
Syntax:
OPEN <file name> FOR <file mode>
WRITE <variable>
CLOSEFILE <file name>

Example:
Copy
FOR I <- 1 TO 10
OPENFILE “file.txt” FOR WRITE
X <- file.txt
WRITE X
NEXT I
CLOSE FILE “file.txt”

String Handling:
● Length - Finds the number of characters in a string Example: Finding the number of
characters in ‘Computer Science’
Copy
LENGTH(“Computer Science”)
Note - text to be written in quotes, variable to be written without quotes
● Substring - Extracting part of a string Example: Extracting the word “Science” from
“Computer Science”
Copy
SUBSTRING(“Computer Science”, 10,7)
Note - space is considered as a character in programming
● Upper - Convert all letters in a string to upper-case Example: Converting the word “Computer
Science” to upper case
Copy
UCASE(“Computer Scince”)
● Lower - Convert all letters in a string to lowercase Example: Converting the word “Computer
Science” to lowercase
Copy
LCASE(“Computer Science”)

RECORD DATA TYPE - AS ONLY :


The Record datatype is a data structure used in computer programming that allows the storage
of multiple values of different data types under a single variable name.
Pseudocode:
TYPE NameOfDatatype
DECLARE Value1 : DATATYPE
DECLARE Value2 : DATATYPE
DECLARE Value3 : DATATYPE
ENDTYPE
Q) Bookinformation is the name of the record datatype It contains :
title: String ISBN: Integer Author: String
Write a record data type pseudocode for these values.
Solution:
TYPE Bookinformation
DECLARE Title: STRING
DECLARE ISBN: INTEGER
DECLARE Author: STRING
ENDTYPE

Q) Create a variable with the name Book1 and datatype Bookinformation


Title: Nerd Cafe ISBN: 1027554
Author: Quin
DECLARE Book1 : Bookinformation

Book1.Title <-----"Nerd Cafe"


Book1.ISBN <----- 1027554
Book1.Author <----- "Quin"

You might also like