0% found this document useful (0 votes)
8 views39 pages

Pseudocode Complete Guide

The 'Pseudocode Complete Reference Guide' provides a comprehensive overview of pseudocode, including its syntax, examples, and practical applications in programming. It covers essential topics such as variables, data types, input/output operations, arithmetic and logical operators, and more, aimed at aiding learners in understanding algorithm design and implementation. The guide adheres to Cambridge International Examinations (CIE) standards, making it suitable for educational purposes.

Uploaded by

walltaweneedcoco
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)
8 views39 pages

Pseudocode Complete Guide

The 'Pseudocode Complete Reference Guide' provides a comprehensive overview of pseudocode, including its syntax, examples, and practical applications in programming. It covers essential topics such as variables, data types, input/output operations, arithmetic and logical operators, and more, aimed at aiding learners in understanding algorithm design and implementation. The guide adheres to Cambridge International Examinations (CIE) standards, making it suitable for educational purposes.

Uploaded by

walltaweneedcoco
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

PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

PSEUDOCODE
Complete Reference Guide
Syntax · Examples · Worked Programs · Exercises

Variables & Data Types Selection Iteration Procedures & Functions

Arrays File Handling OOP Sorting & Searching

Cambridge IGCSE / A-Level Computer Science

Full Coverage · CIE-Style Notation · Worked Examples & Practice

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 1


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

■ TABLE OF CONTENTS

1 Introduction to Pseudocode —

2 Variables, Constants & Data Types —

3 Input and Output —

4 Arithmetic & Operators —

5 Selection — IF / CASE Statements —

6 Iteration — Loops (FOR / WHILE / REPEAT) —

7 Procedures and Functions —

8 Arrays (1D and 2D) —

9 Strings and String Operations —

10 File Handling —

11 Object-Oriented Programming —

12 Sorting Algorithms in Pseudocode —

13 Searching Algorithms in Pseudocode —

14 Common Worked Programs —

15 Common Errors & Best Practices —

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 2


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 Introduction to Pseudocode

Pseudocode is an informal, high-level description of an algorithm or program. It uses structured English


alongside programming constructs so that the logic of a solution can be communicated clearly without worrying
about the precise syntax of any real programming language. It is widely used in education, software design, and
technical interviews to describe algorithms independently of implementation.

Why Use Pseudocode?

• Language-independent: Works for Python, Java, C++, etc. — any language can implement it.
• Human-readable: Easy for non-programmers to understand the logic.
• Design tool: Helps plan algorithms before writing actual code.
• Exam standard: Used in Cambridge IGCSE/A-Level exams as the answer medium.
• Collaborative: Teams can agree on logic without committing to a language.

Pseudocode vs Real Code — Comparison

Feature Pseudocode Real Code (Python example)

Syntax rules Relaxed / informal Strict — errors cause failures

Semicolons Not required Required in some languages

Variable types Often implicit Must be declared explicitly

Print output OUTPUT or PRINT print() in Python

Loops FOR, WHILE, REPEAT for, while (language-specific)

Goal Communicate logic Execute on a computer

CIE Notation Note


This guide uses Cambridge International Examinations (CIE) pseudocode conventions.
Keywords are written in UPPERCASE. Indentation shows structure.
Comments begin with // and are ignored during execution.

General Rules and Conventions

1. Keywords are UPPERCASE (e.g. IF, WHILE, OUTPUT).


2. Variable names use mixed case and should be descriptive (e.g. studentName, totalScore).
3. Indentation (2–4 spaces) is used to show the body of blocks.
4. Comments are written as // This is a comment and explain the intent.
5. Assignment uses ← (arrow) in CIE notation, or = in some styles.
6. String literals are enclosed in double quotes: "Hello World".
7. Character literals use single quotes: 'A'.
8. There is no semicolon at the end of lines.
9. Every block keyword has a matching end keyword (ENDIF, ENDWHILE, ENDFOR, etc.).

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 3


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

2 Variables, Constants & Data Types

A variable is a named memory location that holds a value which can change during program execution. A
constant is a named value that is set once and never changes. Every value stored in memory belongs to a data
type, which defines what kind of data it holds and what operations are allowed on it.

2.1 Declaring Variables

In CIE pseudocode, variables are declared with DECLARE:

1 DECLARE studentName : STRING


2 DECLARE age : INTEGER
3 DECLARE score : REAL
4 DECLARE passed : BOOLEAN
5 DECLARE initial : CHAR
6
7 // Multiple declarations are each on their own line
8 DECLARE counter : INTEGER
9 DECLARE total : REAL
10 DECLARE name : STRING

2.2 Data Types Table

Data Type Keyword Example Values Use Case

Integer INTEGER 0, 42, -7, 1000 Whole numbers, counters, indices

Real/Float REAL 3.14, -0.5, 2.718 Decimal numbers, measurements

Boolean BOOLEAN TRUE, FALSE Flags, conditions, on/off states

Character CHAR 'A', 'z', '7', ' ' Single character storage

String STRING "Hello", "Alice123" Text, names, messages

Date DATE 01/09/2024 Calendar dates (implementation-specific)

2.3 Assignment

The assignment operator ← assigns a value to a variable. In some pseudocode styles = is used instead.

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 4


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // CIE standard notation uses ←


2 studentName ← "Alice"
3 age ← 16
4 score ← 87.5
5 passed ← TRUE
6 initial ← 'A'
7
8 // Assigning the result of an expression
9 total ← price * quantity
10 grade ← score DIV 10
11 name ← firstName & " " & lastName // string concatenation
12
13 // Re-assigning (updating) a variable
14 counter ← counter + 1
15 total ← total - discount

2.4 Constants

Constants are declared with CONSTANT and must be assigned a value at declaration. Their value cannot be
changed later in the program.

1 CONSTANT PI ← 3.14159
2 CONSTANT MAX_SIZE ← 100
3 CONSTANT PASS_MARK ← 50
4 CONSTANT SCHOOL ← "Greenfield Academy"
5
6 // Using constants
7 area ← PI * radius * radius
8 IF score >= PASS_MARK
9 THEN OUTPUT "Pass"
10 ENDIF

Best Practice
Use CONSTANTS for magic numbers — values that appear multiple times and have meaning.
e.g. use MAX_STUDENTS instead of writing 30 repeatedly throughout the code.
This makes code easier to maintain: change the constant once, applies everywhere.

2.5 Type Conversion

Some pseudocode styles include built-in type-conversion functions:

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 5


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Converting between types


2 numStr ← STRING(42) // Integer → String: "42"
3 numInt ← INT("99") // String → Integer: 99
4 numReal ← REAL("3.14") // String → Real: 3.14
5 charVal ← CHR(65) // Integer → Character: 'A' (ASCII)
6 asciiVal← ASC('A') // Character → Integer: 65
7
8 // Implicit / explicit conversion example
9 DECLARE x : INTEGER
10 DECLARE y : REAL
11 x ← 7
12 y ← REAL(x) / 2 // y becomes 3.5 (not 3)

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 6


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

3 Input and Output

Pseudocode programs interact with users through INPUT (reading data) and OUTPUT (displaying data). These
are the two primary I/O keywords in CIE notation.

3.1 OUTPUT Statement

1 // Output a literal string


2 OUTPUT "Hello, World!"
3
4 // Output a variable
5 OUTPUT name
6 OUTPUT score
7
8 // Output a combination (concatenation with &)
9 OUTPUT "Your name is: " & name
10 OUTPUT "Score: " & STRING(score) & " out of 100"
11
12 // Output the result of an expression directly
13 OUTPUT length * width
14 OUTPUT "Average: " & STRING(total / count)
15
16 // Output multiple values (comma-separated in some styles)
17 OUTPUT firstName, " ", lastName
18 OUTPUT "Sum = ", num1 + num2

3.2 INPUT Statement

1 // Read into a variable (user types a value)


2 INPUT name
3 INPUT age
4 INPUT score
5
6 // It is good practice to prompt the user first
7 OUTPUT "Enter your name: "
8 INPUT name
9
10 OUTPUT "Enter your age: "
11 INPUT age
12
13 OUTPUT "Enter the temperature in Celsius: "
14 INPUT celsius
15 fahrenheit ← (celsius * 9 / 5) + 32
16 OUTPUT "Fahrenheit: " & STRING(fahrenheit)

3.3 Complete I/O Example — Greeting Program

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 7


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 DECLARE firstName : STRING


2 DECLARE lastName : STRING
3 DECLARE age : INTEGER
4
5 OUTPUT "=== User Registration ==="
6 OUTPUT "Enter first name: "
7 INPUT firstName
8 OUTPUT "Enter last name: "
9 INPUT lastName
10 OUTPUT "Enter age: "
11 INPUT age
12
13 OUTPUT "Welcome, " & firstName & " " & lastName & "!"
14 OUTPUT "You are " & STRING(age) & " years old."
15
16 IF age >= 18
17 THEN OUTPUT "You are an adult."
18 ELSE OUTPUT "You are a minor."
19 ENDIF

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 8


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

4 Arithmetic & Operators

4.1 Arithmetic Operators

Operator Operation Example Result

+ Addition 5+3 8

- Subtraction 10 - 4 6

* Multiplication 6*7 42

/ Division (real) 7/2 3.5

DIV Integer division 7 DIV 2 3 (quotient only)

MOD Modulus (remainder) 7 MOD 2 1 (remainder only)

^ Exponentiation 2^8 256

4.2 DIV and MOD — Detailed

1 // DIV — integer (whole number) division, discards remainder


2 OUTPUT 17 DIV 5 // Outputs: 3 (5 goes into 17 three times)
3 OUTPUT 20 DIV 4 // Outputs: 5
4 OUTPUT 7 DIV 3 // Outputs: 2
5
6 // MOD — gives the remainder after integer division
7 OUTPUT 17 MOD 5 // Outputs: 2 (17 = 3*5 + 2)
8 OUTPUT 20 MOD 4 // Outputs: 0 (divides evenly)
9 OUTPUT 7 MOD 3 // Outputs: 1 (7 = 2*3 + 1)
10
11 // Practical uses of MOD:
12 // Test if a number is even: number MOD 2 = 0
13 // Get last digit of a number: number MOD 10
14 // Wrap around array indices: index MOD arraySize
15 // Clock arithmetic: (hours + n) MOD 24
16
17 // Example: classify number as odd or even
18 OUTPUT "Enter a number: "
19 INPUT num
20 IF num MOD 2 = 0
21 THEN OUTPUT STRING(num) & " is EVEN"
22 ELSE OUTPUT STRING(num) & " is ODD"
23 ENDIF

4.3 Comparison Operators

Operator Meaning Example Result

= Equal to x=5 TRUE if x is 5

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 9


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

<> Not equal to x <> 3 TRUE if x ≠ 3

< Less than age < 18 TRUE if age under 18

> Greater than score > 50 TRUE if score over 50

<= Less than or equal x <= 10 TRUE if x is ≤ 10

>= Greater than or equal y >= 0 TRUE if y is ≥ 0

4.4 Logical / Boolean Operators

Boolean operators combine or modify conditions. They return TRUE or FALSE.

Operator Usage A B Result

AND A AND B TRUE TRUE TRUE

AND A AND B TRUE FALSE FALSE

AND A AND B FALSE FALSE FALSE

OR A OR B TRUE FALSE TRUE

OR A OR B FALSE FALSE FALSE

NOT NOT A TRUE — FALSE

NOT NOT A FALSE — TRUE

1 // AND — both conditions must be true


2 IF age >= 18 AND age <= 65
3 THEN OUTPUT "Working age adult"
4 ENDIF
5
6 // OR — at least one condition must be true
7 IF grade = 'A' OR grade = 'B'
8 THEN OUTPUT "Merit awarded"
9 ENDIF
10
11 // NOT — reverses the Boolean value
12 IF NOT(isLoggedIn)
13 THEN OUTPUT "Please log in first"
14 ENDIF
15
16 // Combining operators (use brackets for clarity)
17 IF (score >= 80 AND attendance > 90) OR (score >= 95)
18 THEN OUTPUT "Distinction"
19 ENDIF

4.5 Operator Precedence

When an expression has multiple operators, they are evaluated in this order (from highest to lowest
precedence):

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 10


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

Priority Category Operators Example

1st (highest) Brackets / Parentheses () (3 + 4) * 2 = 14

2nd Exponentiation ^ 2^3=8

3rd Unary minus / NOT -, NOT -5, NOT TRUE

4th Multiply, Divide, DIV, MOD *, /, DIV, MOD 6 * 4 DIV 3

5th Add, Subtract +, - 3+4-1

6th Comparison =, <>, <, >, <=, >= x < 10

7th (lowest) Logical AND, OR AND, OR a AND b OR c

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 11


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

5 Selection — IF / CASE Statements

Selection allows a program to make decisions — executing different blocks of code depending on whether a
condition is TRUE or FALSE. CIE pseudocode supports IF…THEN…ELSE…ENDIF for boolean decisions and
CASE…OF…ENDCASE for multi-value choices.

5.1 Simple IF…THEN…ENDIF

1 // Syntax — single branch (no ELSE)


2 IF <condition>
3 THEN
4 <statements if TRUE>
5 ENDIF
6
7 // Example: check if a number is positive
8 OUTPUT "Enter a number: "
9 INPUT number
10 IF number > 0
11 THEN OUTPUT STRING(number) & " is positive."
12 ENDIF

5.2 IF…THEN…ELSE…ENDIF

1 // Syntax — two branches


2 IF <condition>
3 THEN
4 <statements if TRUE>
5 ELSE
6 <statements if FALSE>
7 ENDIF
8
9 // Example: pass or fail
10 CONSTANT PASS_MARK ← 50
11 OUTPUT "Enter your mark: "
12 INPUT mark
13 IF mark >= PASS_MARK
14 THEN
15 OUTPUT "PASS — well done!"
16 OUTPUT "Your mark: " & STRING(mark)
17 ELSE
18 OUTPUT "FAIL — try again."
19 OUTPUT "You need " & STRING(PASS_MARK - mark) & " more marks."
20 ENDIF

5.3 Nested IF — Multiple Conditions

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 12


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Nested IF using ELSEIF (or nested ELSE blocks)


2 OUTPUT "Enter score (0-100): "
3 INPUT score
4
5 IF score >= 90
6 THEN OUTPUT "Grade: A*"
7 ELSE IF score >= 80
8 THEN OUTPUT "Grade: A"
9 ELSE IF score >= 70
10 THEN OUTPUT "Grade: B"
11 ELSE IF score >= 60
12 THEN OUTPUT "Grade: C"
13 ELSE IF score >= 50
14 THEN OUTPUT "Grade: D"
15 ELSE OUTPUT "Grade: U (ungraded)"
16 ENDIF
17 ENDIF
18 ENDIF
19 ENDIF
20 ENDIF

5.4 CASE…OF…ENDCASE

CASE is used when a variable is compared against several possible values. It is cleaner than deeply nested IF
statements for this situation.

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 13


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Syntax
2 CASE <variable> OF
3 <value1> : <statement>
4 <value2> : <statement>
5 <value3> : <statement>
6 OTHERWISE : <default statement>
7 ENDCASE
8
9 // Example 1: Day of the week
10 OUTPUT "Enter day number (1–7): "
11 INPUT dayNum
12 CASE dayNum OF
13 1 : OUTPUT "Monday"
14 2 : OUTPUT "Tuesday"
15 3 : OUTPUT "Wednesday"
16 4 : OUTPUT "Thursday"
17 5 : OUTPUT "Friday"
18 6 : OUTPUT "Saturday"
19 7 : OUTPUT "Sunday"
20 OTHERWISE : OUTPUT "Invalid day number"
21 ENDCASE
22
23 // Example 2: Menu selection
24 OUTPUT "1. New Game 2. Load Game 3. Settings 4. Quit"
25 OUTPUT "Choose option: "
26 INPUT choice
27 CASE choice OF
28 1 : CALL StartNewGame()
29 2 : CALL LoadGame()
30 3 : CALL ShowSettings()
31 4 : OUTPUT "Goodbye!"
32 OTHERWISE : OUTPUT "Invalid option. Please choose 1–4."
33 ENDCASE

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 14


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

6 Iteration — FOR / WHILE / REPEAT Loops

Iteration (looping) allows a block of code to be executed repeatedly. CIE pseudocode provides three types of
loop, each suited to different situations: FOR…NEXT (count-controlled), WHILE…ENDWHILE (pre-condition),
and REPEAT…UNTIL (post-condition).

6.1 FOR…TO…NEXT (Count-Controlled Loop)

Use when you know exactly how many times the loop should run.

1 // Syntax
2 FOR <variable> ← <start> TO <end>
3 <statements>
4 NEXT <variable>
5
6 // Example 1: Count from 1 to 10
7 FOR i ← 1 TO 10
8 OUTPUT i
9 NEXT i
10
11 // Example 2: Sum of first N numbers
12 OUTPUT "How many numbers? "
13 INPUT n
14 total ← 0
15 FOR i ← 1 TO n
16 total ← total + i
17 NEXT i
18 OUTPUT "Sum = " & STRING(total)
19
20 // With STEP — count by 2s
21 FOR i ← 2 TO 20 STEP 2
22 OUTPUT i
23 NEXT i
24
25 // Counting backwards (negative STEP)
26 FOR i ← 10 TO 1 STEP -1
27 OUTPUT STRING(i) & "..."
28 NEXT i
29 OUTPUT "Blast off!"

6.2 WHILE…ENDWHILE (Pre-Condition Loop)

Use when the loop should run zero or more times, and the condition is checked before each iteration.

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 15


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Syntax
2 WHILE <condition>
3 <statements>
4 ENDWHILE
5
6 // Example 1: Input validation (keep asking until valid)
7 OUTPUT "Enter a positive number: "
8 INPUT number
9 WHILE number <= 0
10 OUTPUT "Invalid! Enter a positive number: "
11 INPUT number
12 ENDWHILE
13 OUTPUT "You entered: " & STRING(number)
14
15 // Example 2: Guessing game
16 CONSTANT SECRET ← 42
17 DECLARE guess : INTEGER
18 DECLARE attempts: INTEGER
19 attempts ← 0
20 guess ← 0
21 WHILE guess <> SECRET
22 OUTPUT "Guess the number: "
23 INPUT guess
24 attempts ← attempts + 1
25 IF guess < SECRET
26 THEN OUTPUT "Too low!"
27 ELSE IF guess > SECRET
28 THEN OUTPUT "Too high!"
29 ENDIF
30 ENDIF
31 ENDWHILE
32 OUTPUT "Correct! Took " & STRING(attempts) & " attempts."

6.3 REPEAT…UNTIL (Post-Condition Loop)

Use when the loop must execute at least once, and the condition is checked after each iteration.

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 16


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Syntax
2 REPEAT
3 <statements>
4 UNTIL <condition>
5
6 // Example 1: Menu that keeps showing until user quits
7 REPEAT
8 OUTPUT "=== MENU ==="
9 OUTPUT "1. Play 2. Settings 3. Quit"
10 INPUT choice
11 CASE choice OF
12 1 : CALL PlayGame()
13 2 : CALL ShowSettings()
14 3 : OUTPUT "Goodbye!"
15 OTHERWISE : OUTPUT "Invalid choice."
16 ENDCASE
17 UNTIL choice = 3
18
19 // Example 2: Read passwords until correct
20 CONSTANT CORRECT_PIN ← 1234
21 REPEAT
22 OUTPUT "Enter PIN: "
23 INPUT pin
24 IF pin <> CORRECT_PIN
25 THEN OUTPUT "Wrong PIN. Try again."
26 ENDIF
27 UNTIL pin = CORRECT_PIN
28 OUTPUT "Access granted."

6.4 Loop Comparison Table

Loop Type Check Runs at least once? Best Used For

FOR…NEXT Before (count) No — if end < start Known number of iterations

WHILE…ENDWHILE Before (condition) No — may skip entirely Unknown iterations, check first

REPEAT…UNTIL After (condition) YES — always once Menu-driven, validate input

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 17


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

7 Procedures and Functions

Procedures and functions are named blocks of reusable code. A PROCEDURE performs a task but does not
return a value. A FUNCTION performs a task AND returns a single value. Both accept parameters (inputs).
Using them reduces repetition and improves readability.

7.1 PROCEDURE — Definition and Call

1 // Syntax: define a procedure


2 PROCEDURE <name>(<param1>: <type>, <param2>: <type>, ...)
3 <statements>
4 ENDPROCEDURE
5
6 // Syntax: call a procedure
7 CALL <name>(<argument1>, <argument2>, ...)
8
9 // Example 1: Procedure with no parameters
10 PROCEDURE DisplayHeader()
11 OUTPUT "========================"
12 OUTPUT " STUDENT GRADE SYSTEM "
13 OUTPUT "========================"
14 ENDPROCEDURE
15
16 CALL DisplayHeader()
17
18 // Example 2: Procedure with parameters
19 PROCEDURE Greet(firstName: STRING, age: INTEGER)
20 OUTPUT "Hello, " & firstName & "!"
21 OUTPUT "You are " & STRING(age) & " years old."
22 IF age >= 18
23 THEN OUTPUT "You are an adult."
24 ELSE OUTPUT "You are a minor."
25 ENDIF
26 ENDPROCEDURE
27
28 CALL Greet("Alice", 16)
29 CALL Greet("Bob", 21)

7.2 FUNCTION — Definition and Call

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 18


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Syntax: define a function


2 FUNCTION <name>(<params>) RETURNS <type>
3 <statements>
4 RETURN <value>
5 ENDFUNCTION
6
7 // Syntax: call a function (use the return value)
8 result ← <name>(<arguments>)
9
10 // Example 1: Calculate area of a rectangle
11 FUNCTION CalculateArea(length: REAL, width: REAL) RETURNS REAL
12 DECLARE area : REAL
13 area ← length * width
14 RETURN area
15 ENDFUNCTION
16
17 // Using the function
18 roomArea ← CalculateArea(5.0, 3.5)
19 OUTPUT "Room area: " & STRING(roomArea) & " m²"
20
21 // Example 2: Find maximum of two numbers
22 FUNCTION Maximum(a: INTEGER, b: INTEGER) RETURNS INTEGER
23 IF a > b
24 THEN RETURN a
25 ELSE RETURN b
26 ENDIF
27 ENDFUNCTION
28
29 OUTPUT "Max of 14, 27 is: " & STRING(Maximum(14, 27))
30
31 // Example 3: Check if a number is prime
32 FUNCTION IsPrime(n: INTEGER) RETURNS BOOLEAN
33 DECLARE i : INTEGER
34 IF n < 2
35 THEN RETURN FALSE
36 ENDIF
37 FOR i ← 2 TO n - 1
38 IF n MOD i = 0
39 THEN RETURN FALSE
40 ENDIF
41 NEXT i
42 RETURN TRUE
43 ENDFUNCTION

7.3 Passing by Value vs by Reference

Parameters can be passed BYVAL (a copy — changes inside do NOT affect the original) or BYREF (a
reference — changes inside DO affect the original).

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 19


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // BYVAL — default. Changes inside don't affect outside


2 PROCEDURE DoubleIt(BYVAL x: INTEGER)
3 x ← x * 2
4 OUTPUT "Inside: " & STRING(x)
5 ENDPROCEDURE
6
7 num ← 5
8 CALL DoubleIt(num)
9 OUTPUT "Outside: " & STRING(num) // Still 5 — unchanged
10
11 // BYREF — changes made inside WILL affect the original variable
12 PROCEDURE TrippleIt(BYREF x: INTEGER)
13 x ← x * 3
14 ENDPROCEDURE
15
16 num ← 5
17 CALL TrippleIt(num)
18 OUTPUT "Outside: " & STRING(num) // Now 15 — changed!

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 20


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

8 Arrays (1D and 2D)

An array is a fixed-size collection of elements of the same data type, stored under a single variable name.
Elements are accessed by their index (position number). In CIE pseudocode, arrays are typically 1-indexed
(start at 1) unless otherwise specified.

8.1 Declaring and Using 1D Arrays

1 // Syntax: DECLARE <name> : ARRAY[<start>:<end>] OF <type>


2 DECLARE scores : ARRAY[1:10] OF INTEGER
3 DECLARE names : ARRAY[1:5] OF STRING
4 DECLARE temperatures: ARRAY[0:6] OF REAL
5
6 // Assign values to individual elements
7 scores[1] ← 85
8 scores[2] ← 72
9 scores[3] ← 90
10 names[1] ← "Alice"
11 names[2] ← "Bob"
12
13 // Access (read) an element
14 OUTPUT scores[1] // Outputs: 85
15 OUTPUT names[1] // Outputs: Alice
16
17 // Fill array using a FOR loop
18 FOR i ← 1 TO 10
19 OUTPUT "Enter score " & STRING(i) & ": "
20 INPUT scores[i]
21 NEXT i
22
23 // Print all elements
24 FOR i ← 1 TO 10
25 OUTPUT "Score " & STRING(i) & ": " & STRING(scores[i])
26 NEXT i
27
28 // Calculate total and average
29 total ← 0
30 FOR i ← 1 TO 10
31 total ← total + scores[i]
32 NEXT i
33 average ← total / 10
34 OUTPUT "Average score: " & STRING(average)

8.2 2D Arrays (Matrices / Grids)

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 21


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Syntax: DECLARE <name> : ARRAY[<r1>:<r2>, <c1>:<c2>] OF <type>


2 DECLARE grid : ARRAY[1:3, 1:3] OF INTEGER // 3x3 grid
3 DECLARE seating : ARRAY[1:5, 1:8] OF STRING // 5 rows, 8 cols
4
5 // Assign values
6 grid[1,1] ← 1 grid[1,2] ← 2 grid[1,3] ← 3
7 grid[2,1] ← 4 grid[2,2] ← 5 grid[2,3] ← 6
8 grid[3,1] ← 7 grid[3,2] ← 8 grid[3,3] ← 9
9
10 // Nested loop to fill 2D array
11 FOR row ← 1 TO 3
12 FOR col ← 1 TO 3
13 OUTPUT "Enter grid[" & STRING(row) & "," & STRING(col) & "]: "
14 INPUT grid[row, col]
15 NEXT col
16 NEXT row
17
18 // Print 2D array as a table
19 FOR row ← 1 TO 3
20 FOR col ← 1 TO 3
21 OUTPUT grid[row, col] & " "
22 NEXT col
23 OUTPUT "" // newline after each row
24 NEXT row
25
26 // Find sum of all elements
27 sum ← 0
28 FOR row ← 1 TO 3
29 FOR col ← 1 TO 3
30 sum ← sum + grid[row, col]
31 NEXT col
32 NEXT row
33 OUTPUT "Total sum: " & STRING(sum)

8.3 Array Algorithms — Find Min, Max, Linear Search

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 22


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Find the maximum value in an array


2 maxVal ← scores[1]
3 FOR i ← 2 TO 10
4 IF scores[i] > maxVal
5 THEN maxVal ← scores[i]
6 ENDIF
7 NEXT i
8 OUTPUT "Max score: " & STRING(maxVal)
9
10 // Linear search — find a target value
11 DECLARE found : BOOLEAN
12 DECLARE position: INTEGER
13 target ← 90
14 found ← FALSE
15 FOR i ← 1 TO 10
16 IF scores[i] = target
17 THEN
18 found ← TRUE
19 position ← i
20 ENDIF
21 NEXT i
22 IF found
23 THEN OUTPUT "Found " & STRING(target) & " at index " & STRING(position)
24 ELSE OUTPUT STRING(target) & " not found."
25 ENDIF

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 23


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

9 Strings and String Operations

Strings are sequences of characters. CIE pseudocode provides built-in string functions for manipulating text.
These are commonly tested in exams.

9.1 String Functions Reference

Function Syntax Returns Example

INTEGER — number of
LENGTH LENGTH(str) chars LENGTH("Hello") → 5

UCASE UCASE(str) STRING — all uppercase UCASE("hello") → "HELLO"

LCASE LCASE(str) STRING — all lowercase LCASE("HELLO") → "hello"

SUBSTRING(str, start,
SUBSTRING len) STRING — portion of str SUBSTRING("Hello", 2, 3) → "ell"

LEFT LEFT(str, n) STRING — first n chars LEFT("Hello", 3) → "Hel"

RIGHT RIGHT(str, n) STRING — last n chars RIGHT("Hello", 3) → "llo"

MID MID(str, start, len) STRING — middle portion MID("Hello", 2, 3) → "ell"

& str1 & str2 STRING — concatenation "Hi" & " " & "Bob" → "Hi Bob"

STRING() STRING(num) STRING from a number STRING(42) → "42"

INT() INT(str) INTEGER from a string INT("99") → 99

9.2 String Manipulation Examples

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 24


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 DECLARE fullName : STRING


2 DECLARE email : STRING
3 DECLARE initial : STRING
4
5 fullName ← "Alice Johnson"
6
7 // Length
8 OUTPUT LENGTH(fullName) // 13
9
10 // Upper/lower case
11 OUTPUT UCASE(fullName) // ALICE JOHNSON
12 OUTPUT LCASE(fullName) // alice johnson
13
14 // Extract first name (characters before the space)
15 spacePos ← 1
16 FOR i ← 1 TO LENGTH(fullName)
17 IF SUBSTRING(fullName, i, 1) = " "
18 THEN spacePos ← i
19 ENDIF
20 NEXT i
21 firstName ← LEFT(fullName, spacePos - 1)
22 lastName ← RIGHT(fullName, LENGTH(fullName) - spacePos)
23 OUTPUT "First: " & firstName // Alice
24 OUTPUT "Last: " & lastName // Johnson
25
26 // Get initials
27 initial ← LEFT(firstName, 1) & "." & LEFT(lastName, 1) & "."
28 OUTPUT initial // A.J.
29
30 // Build email address
31 email ← LCASE(firstName) & "." & LCASE(lastName) & "@[Link]"
32 OUTPUT email // [Link]@[Link]

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 25


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

10 File Handling

File handling allows programs to store data permanently (persistence) between runs. CIE pseudocode uses
OPENFILE, READFILE, WRITEFILE, and CLOSEFILE. Files must be opened before use and closed after.

10.1 File Operations Summary

Statement Purpose Mode

OPENFILE file FOR READ Open existing file to read from READ

OPENFILE file FOR WRITE Create/overwrite file to write to WRITE

OPENFILE file FOR APPEND Add to end of an existing file APPEND

READFILE file, variable Read next line into variable READ

WRITE /
WRITEFILE file, data Write a line to the file APPEND

CLOSEFILE file Close the file when done Any

EOF(file) Returns TRUE if end of file reached READ

10.2 Writing to a File

1 // Write student names to a file


2 DECLARE name : STRING
3 DECLARE i : INTEGER
4
5 OPENFILE "[Link]" FOR WRITE
6 FOR i ← 1 TO 5
7 OUTPUT "Enter name " & STRING(i) & ": "
8 INPUT name
9 WRITEFILE "[Link]", name
10 NEXT i
11 CLOSEFILE "[Link]"
12 OUTPUT "File saved successfully."

10.3 Reading from a File

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 26


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Read all students from file until end


2 DECLARE name : STRING
3 DECLARE count : INTEGER
4 count ← 0
5
6 OPENFILE "[Link]" FOR READ
7 WHILE NOT EOF("[Link]")
8 READFILE "[Link]", name
9 OUTPUT name
10 count ← count + 1
11 ENDWHILE
12 CLOSEFILE "[Link]"
13 OUTPUT "Total students read: " & STRING(count)

10.4 Append to a File

1 // Add new record to existing file


2 DECLARE newStudent : STRING
3 OUTPUT "Enter new student name: "
4 INPUT newStudent
5
6 OPENFILE "[Link]" FOR APPEND
7 WRITEFILE "[Link]", newStudent
8 CLOSEFILE "[Link]"
9 OUTPUT newStudent & " added to file."

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 27


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

11 Object-Oriented Programming

OOP organises code into classes (blueprints) and objects (instances). A class bundles data (attributes) with
behaviour (methods). CIE A-Level pseudocode supports CLASS, constructor methods, access modifiers, and
INHERITS.

11.1 Defining a Class

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 28


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 CLASS Animal
2 PRIVATE name : STRING
3 PRIVATE age : INTEGER
4 PRIVATE species: STRING
5
6 // Constructor — called when object is created
7 PUBLIC PROCEDURE NEW(n: STRING, a: INTEGER, s: STRING)
8 name ← n
9 age ← a
10 species ← s
11 ENDPROCEDURE
12
13 // Getter methods
14 PUBLIC FUNCTION GetName() RETURNS STRING
15 RETURN name
16 ENDFUNCTION
17
18 PUBLIC FUNCTION GetAge() RETURNS INTEGER
19 RETURN age
20 ENDFUNCTION
21
22 // Setter method
23 PUBLIC PROCEDURE SetAge(newAge: INTEGER)
24 IF newAge >= 0
25 THEN age ← newAge
26 ELSE OUTPUT "Invalid age"
27 ENDIF
28 ENDPROCEDURE
29
30 // Regular method
31 PUBLIC PROCEDURE Describe()
32 OUTPUT name & " is a " & species & ", age " & STRING(age)
33 ENDPROCEDURE
34
35 ENDCLASS
36
37 // Creating and using objects
38 DECLARE myPet : Animal
39 myPet ← NEW Animal("Buddy", 3, "Golden Retriever")
40 CALL [Link]()
41 OUTPUT [Link]()
42 CALL [Link](4)

11.2 Inheritance

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 29


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Subclass inherits from Animal


2 CLASS Dog INHERITS Animal
3 PRIVATE breed : STRING
4
5 PUBLIC PROCEDURE NEW(n: STRING, a: INTEGER, b: STRING)
6 CALL [Link](n, a, "Dog") // Call parent constructor
7 breed ← b
8 ENDPROCEDURE
9
10 PUBLIC PROCEDURE Bark()
11 OUTPUT GetName() & " says: Woof!"
12 ENDPROCEDURE
13
14 PUBLIC FUNCTION GetBreed() RETURNS STRING
15 RETURN breed
16 ENDFUNCTION
17
18 ENDCLASS
19
20 DECLARE rex : Dog
21 rex ← NEW Dog("Rex", 2, "German Shepherd")
22 CALL [Link]() // Inherited from Animal
23 CALL [Link]() // Dog's own method
24 OUTPUT [Link]() // German Shepherd

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 30


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

12 Sorting Algorithms in Pseudocode

12.1 Bubble Sort

Bubble Sort repeatedly steps through the list, compares adjacent elements and swaps them if they are in the
wrong order. Each full pass 'bubbles' the largest unsorted element to its correct position. Time complexity: O(n²).

1 PROCEDURE BubbleSort(BYREF arr: ARRAY[1:n] OF INTEGER, n: INTEGER)


2 DECLARE i, j, temp : INTEGER
3 DECLARE swapped : BOOLEAN
4
5 FOR i ← 1 TO n - 1
6 swapped ← FALSE
7 FOR j ← 1 TO n - i
8 IF arr[j] > arr[j+1]
9 THEN
10 // Swap arr[j] and arr[j+1]
11 temp ← arr[j]
12 arr[j] ← arr[j+1]
13 arr[j+1] ← temp
14 swapped ← TRUE
15 ENDIF
16 NEXT j
17 // Optimisation: stop if no swaps in this pass
18 IF NOT swapped
19 THEN // Array is sorted — exit early
20 // (In pseudocode we continue; no BREAK keyword in CIE)
21 ENDIF
22 NEXT i
23 ENDPROCEDURE

12.2 Insertion Sort

Insertion Sort builds a sorted list one element at a time by inserting each element into its correct position among
previously sorted elements. Time complexity: O(n²).

1 PROCEDURE InsertionSort(BYREF arr: ARRAY[1:n] OF INTEGER, n: INTEGER)


2 DECLARE i, j, key : INTEGER
3
4 FOR i ← 2 TO n
5 key ← arr[i]
6 j ← i - 1
7 WHILE j >= 1 AND arr[j] > key
8 arr[j+1] ← arr[j]
9 j ← j - 1
10 ENDWHILE
11 arr[j+1] ← key
12 NEXT i
13 ENDPROCEDURE

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 31


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

12.3 Merge Sort (Divide & Conquer)

Merge Sort divides the array in half, recursively sorts each half, then merges them. Time complexity: O(n log n).

1 PROCEDURE MergeSort(BYREF arr: ARRAY[1:n] OF INTEGER, left, right: INTEGER)


2 IF left < right
3 THEN
4 mid ← (left + right) DIV 2
5 CALL MergeSort(arr, left, mid)
6 CALL MergeSort(arr, mid + 1, right)
7 CALL Merge(arr, left, mid, right)
8 ENDIF
9 ENDPROCEDURE
10
11 PROCEDURE Merge(BYREF arr, left, mid, right: INTEGER)
12 DECLARE temp : ARRAY[1:right] OF INTEGER
13 DECLARE i, j, k : INTEGER
14 i ← left j ← mid + 1 k ← left
15 WHILE i <= mid AND j <= right
16 IF arr[i] <= arr[j]
17 THEN temp[k] ← arr[i] i ← i + 1
18 ELSE temp[k] ← arr[j] j ← j + 1
19 ENDIF
20 k ← k + 1
21 ENDWHILE
22 WHILE i <= mid
23 temp[k] ← arr[i] i ← i + 1 k ← k + 1
24 ENDWHILE
25 WHILE j <= right
26 temp[k] ← arr[j] j ← j + 1 k ← k + 1
27 ENDWHILE
28 FOR i ← left TO right
29 arr[i] ← temp[i]
30 NEXT i
31 ENDPROCEDURE

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 32


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

13 Searching Algorithms in Pseudocode

13.1 Linear Search

Linear (Sequential) Search checks every element one by one. Works on unsorted and sorted arrays. Time
complexity: O(n).

1 FUNCTION LinearSearch(arr: ARRAY[1:n] OF INTEGER, n: INTEGER,


2 target: INTEGER) RETURNS INTEGER
3 // Returns index of target, or -1 if not found
4 DECLARE i : INTEGER
5 FOR i ← 1 TO n
6 IF arr[i] = target
7 THEN RETURN i
8 ENDIF
9 NEXT i
10 RETURN -1
11 ENDFUNCTION
12
13 // Using the function
14 pos ← LinearSearch(scores, 10, 85)
15 IF pos = -1
16 THEN OUTPUT "Not found"
17 ELSE OUTPUT "Found at index " & STRING(pos)
18 ENDIF

13.2 Binary Search

Binary Search works ONLY on sorted arrays. It repeatedly halves the search space by comparing the target to
the middle element. Time complexity: O(log n).

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 33


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 FUNCTION BinarySearch(arr: ARRAY[1:n] OF INTEGER, n: INTEGER,


2 target: INTEGER) RETURNS INTEGER
3 DECLARE low, high, mid : INTEGER
4 low ← 1
5 high ← n
6
7 WHILE low <= high
8 mid ← (low + high) DIV 2
9 IF arr[mid] = target
10 THEN RETURN mid // Found!
11 ELSE IF arr[mid] < target
12 THEN low ← mid + 1 // Target in upper half
13 ELSE high ← mid - 1 // Target in lower half
14 ENDIF
15 ENDIF
16 ENDWHILE
17
18 RETURN -1 // Not found
19 ENDFUNCTION
20
21 // Binary search requires sorted array first!
22 CALL BubbleSort(scores, 10)
23 pos ← BinarySearch(scores, 10, 72)
24 IF pos = -1
25 THEN OUTPUT "Score 72 not found"
26 ELSE OUTPUT "Score 72 at position " & STRING(pos)
27 ENDIF

13.3 Search Algorithm Comparison

Algorithm Sorted Required? Best Case Worst Case Notes

O(n) — last/not Simple, works on any


Linear Search No O(1) — first item found data

O(1) — middle Much faster for large


Binary Search YES item O(log n) arrays

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 34


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

14 Common Worked Programs

14.1 Grade Calculator (Full Program)

1 // Full grade calculator program


2 DECLARE numStudents : INTEGER
3 DECLARE i, score : INTEGER
4 DECLARE total, avg : REAL
5 DECLARE grade : STRING
6 DECLARE name : STRING
7
8 FUNCTION GetGrade(s: INTEGER) RETURNS STRING
9 IF s >= 90 THEN RETURN "A*"
10 ELSE IF s >= 80 THEN RETURN "A"
11 ELSE IF s >= 70 THEN RETURN "B"
12 ELSE IF s >= 60 THEN RETURN "C"
13 ELSE IF s >= 50 THEN RETURN "D"
14 ELSE RETURN "U"
15 ENDIF ENDIF ENDIF ENDIF ENDIF
16 ENDFUNCTION
17
18 OUTPUT "How many students? "
19 INPUT numStudents
20 total ← 0
21
22 FOR i ← 1 TO numStudents
23 OUTPUT "Student " & STRING(i) & " name: "
24 INPUT name
25 OUTPUT "Enter score (0-100): "
26 INPUT score
27 WHILE score < 0 OR score > 100
28 OUTPUT "Invalid score. Re-enter: "
29 INPUT score
30 ENDWHILE
31 grade ← GetGrade(score)
32 OUTPUT name & ": " & STRING(score) & " -> " & grade
33 total ← total + score
34 NEXT i
35
36 avg ← total / numStudents
37 OUTPUT "=== Class Summary ==="
38 OUTPUT "Average score: " & STRING(avg)
39 OUTPUT "Class grade: " & GetGrade(INT(avg))

14.2 Number Guessing Game

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 35


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

1 // Random number guessing game with limited attempts


2 CONSTANT MAX_ATTEMPTS ← 7
3 CONSTANT ANSWER ← 64 // Normally would use RANDOM(1,100)
4
5 DECLARE guess : INTEGER
6 DECLARE attempts : INTEGER
7 DECLARE won : BOOLEAN
8
9 attempts ← 0
10 won ← FALSE
11
12 OUTPUT "=== NUMBER GUESSING GAME ==="
13 OUTPUT "I'm thinking of a number between 1 and 100."
14 OUTPUT "You have " & STRING(MAX_ATTEMPTS) & " attempts. Good luck!"
15
16 WHILE attempts < MAX_ATTEMPTS AND NOT won
17 attempts ← attempts + 1
18 OUTPUT "Attempt " & STRING(attempts) & "/" & STRING(MAX_ATTEMPTS) & ": "
19 INPUT guess
20 IF guess = ANSWER
21 THEN
22 OUTPUT "CORRECT! Well done!"
23 won ← TRUE
24 ELSE IF guess < ANSWER
25 THEN OUTPUT "Too low! Try higher."
26 ELSE OUTPUT "Too high! Try lower."
27 ENDIF
28 ENDIF
29 ENDWHILE
30
31 IF NOT won
32 THEN OUTPUT "Game over! The answer was " & STRING(ANSWER)
33 ENDIF

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 36


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

14.3 Simple Stack Implementation

1 // Stack: Last In, First Out (LIFO) data structure


2 CONSTANT MAX ← 10
3 DECLARE stack : ARRAY[1:MAX] OF INTEGER
4 DECLARE top : INTEGER
5 top ← 0 // Empty stack
6
7 PROCEDURE Push(value: INTEGER)
8 IF top = MAX
9 THEN OUTPUT "Stack overflow — full!"
10 ELSE
11 top ← top + 1
12 stack[top] ← value
13 OUTPUT STRING(value) & " pushed onto stack."
14 ENDIF
15 ENDPROCEDURE
16
17 FUNCTION Pop() RETURNS INTEGER
18 IF top = 0
19 THEN
20 OUTPUT "Stack underflow — empty!"
21 RETURN -1
22 ELSE
23 DECLARE val : INTEGER
24 val ← stack[top]
25 top ← top - 1
26 RETURN val
27 ENDIF
28 ENDFUNCTION
29
30 FUNCTION Peek() RETURNS INTEGER
31 IF top = 0
32 THEN RETURN -1
33 ELSE RETURN stack[top]
34 ENDIF
35 ENDFUNCTION
36
37 // Test the stack
38 CALL Push(10)
39 CALL Push(20)
40 CALL Push(30)
41 OUTPUT "Top item: " & STRING(Peek())
42 OUTPUT "Popped: " & STRING(Pop())
43 OUTPUT "Popped: " & STRING(Pop())
44 OUTPUT "Top item now: " & STRING(Peek())

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 37


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

15 Common Errors & Best Practices

15.1 Common Pseudocode Mistakes

Error Type Wrong Example Correct Example

Missing ENDIF IF x > 0 IF x > 0


THEN OUTPUT x THEN OUTPUT x
ENDIF

Using = for inequality IF x = TRUE IF x = TRUE (OK)


IF x (also OK for BOOLEAN)

Wrong loop var in NEXT FOR i ← 1 TO 10 FOR i ← 1 TO 10


NEXT j NEXT i

No RETURN in FUNCTION Add(a,b) FUNCTION Add(a,b)


FUNCTION result ← a+b RETURN a + b
ENDFUNCTION ENDFUNCTION

Off-by-one in arrays ARRAY[1:10] ARRAY[1:10]


FOR i ← 0 TO 10 FOR i ← 1 TO 10

Forgetting CLOSEFILE OPENFILE f FOR READ OPENFILE f FOR READ


READFILE f, x READFILE f, x
CLOSEFILE f

15.2 Best Practice Checklist

✓ Always declare variables before using them (DECLARE x : INTEGER).


✓ Use meaningful variable names: studentScore not ss or x.
✓ Add comments (// ...) to explain non-obvious logic.
✓ Validate all user input — use WHILE loops to reject invalid values.
✓ Use CONSTANTS for values that appear multiple times (PASS_MARK, MAX_SIZE).
✓ Always close files after opening them (CLOSEFILE).
✓ Indent the body of every block (IF, WHILE, FOR, PROCEDURE) consistently.
✓ Match every opening keyword with its closing keyword (ENDIF, ENDWHILE, etc.).
✓ Use BYREF only when you intend a procedure to modify the caller's variable.
✓ Test boundary values: 0, 1, maximum, and just-below-maximum.
✓ Break long programs into PROCEDURES and FUNCTIONS — one task per unit.
✓ Write trace tables to manually check algorithm logic before coding.

Exam Tip
In CIE exams, marks are given for CORRECT KEYWORDS (IF, THEN, ELSE, ENDIF etc.),
CORRECT INDENTATION, correct LOGIC, and use of proper VARIABLE NAMES.
You will lose marks for missing ENDIF/ENDWHILE/ENDFOR/ENDPROCEDURE/ENDFUNCTION.

15.3 Quick Syntax Reference Card

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 38


PSEUDOCODE — COMPLETE REFERENCE GUIDE Computer Science · Programming Fundamentals

Construct Syntax Template

Variable DECLARE name : TYPE

Constant CONSTANT NAME ← value

Assignment variable ← expression

Output OUTPUT "text" & variable

Input INPUT variable

IF (simple) IF cond THEN ... ENDIF

IF (full) IF cond THEN ... ELSE ... ENDIF

CASE CASE var OF value: stmt OTHERWISE: stmt ENDCASE

FOR loop FOR i ← start TO end STEP n ... NEXT i

WHILE loop WHILE condition ... ENDWHILE

REPEAT loop REPEAT ... UNTIL condition

Procedure PROCEDURE name(params) ... ENDPROCEDURE

Function FUNCTION name(params) RETURNS type RETURN val ENDFUNCTION

Call CALL name(args) or result ← name(args)

Array 1D DECLARE arr : ARRAY[1:n] OF TYPE

Array 2D DECLARE arr : ARRAY[1:r, 1:c] OF TYPE

Open file OPENFILE fname FOR READ/WRITE/APPEND

Read file READFILE fname, variable

Write file WRITEFILE fname, data

Close file CLOSEFILE fname

Class CLASS name ... ENDCLASS

Inherit CLASS Child INHERITS Parent

© Pseudocode Complete Reference Guide Full Syntax · Examples · Exercises Page 39

You might also like