🔒 CS Paper 2 Revision

Enter your name and the class password to continue.

Paper 2 • Computer Science

Algorithms, Pseudocode & Data Structures

CS revision created by Tr.WaiLinHtet

⌂ Home 📄 Paper 1

Program Development Life Cycle (SDLC)

The standard stages followed when developing a program:

  • Analysis: Understand the problem and define requirements.
  • Design: Plan the solution using pseudocode, flowcharts or structure diagrams.
  • Coding: Write the program in a programming language.
  • Testing: Check the program works correctly using test data.
  • Maintenance: Fix errors and improve the program after release.

Program Structure: IPO

Every program can be broken down into three stages:

  • Input: Data entered into the program (e.g. keyboard, sensor, file).
  • Process: Calculations and decisions performed on the data.
  • Output: Results displayed or stored (e.g. screen, file, printer).

Design tools used to plan a solution before coding include flowcharts (symbols and flowlines showing the logic) and structure diagrams (hierarchical diagrams that break a problem down into smaller sub-tasks / modules).

Data Types

Data TypeKeywordExample
IntegerINTEGER5, -12, 100
Real / FloatREAL3.14, -0.5, 99.9
CharacterCHAR'A', 'x', '7'
StringSTRING"Hello", "S1045"
BooleanBOOLEANTRUE, FALSE

Variables & Constants

Variable: A named storage location whose value can change while the program runs.

Constant: A named storage location whose value stays the same throughout the program.

DECLARE Score : INTEGER      // variable
CONSTANT VAT = 0.20          // constant

Operators

Arithmetic: + add, - subtract, * multiply, / divide, DIV integer division, MOD remainder

Comparison: > < = >= <= <>

Logical: AND (both true), OR (either true), NOT (opposite)

▶ Interactive Step-by-Step Visualizer

Ready — click "Next Step" or "Play".
Pseudocode
Variable Trace Table

Selection: IF...THEN...ELSE...ENDIF

IF Age < 18 THEN
  OUTPUT "Child"
ELSE
  OUTPUT "Adult"
ENDIF

CASE OF Move
  'W' : Position ← Position - 10
  'S' : Position ← Position + 10
  OTHERWISE : CALL Beep
ENDCASE

Iteration / Looping

FOR...TO...NEXT

Used when the number of iterations is fixed / known in advance.

FOR Counter ← 1 TO 10
  OUTPUT Counter
NEXT Counter

WHILE...DO...ENDWHILE

Condition checked before the loop runs - body may execute zero times.

Total ← 0
INPUT Mark
WHILE Mark <> -1 DO
  Total ← Total + Mark
  INPUT Mark
ENDWHILE

REPEAT...UNTIL

Condition checked after the loop runs - body always executes at least once.

REPEAT
  OUTPUT "Enter -1 to stop"
  INPUT Option
UNTIL Option = -1

Maximum & Minimum Finder

Initializes both values to the first element and updates them sequentially.

MaximumValue ← Array[1]
MinimumValue ← Array[1]

FOR Counter ← 2 TO LoopLimit
  IF Array[Counter] > MaximumValue THEN
    MaximumValue ← Array[Counter]
  ENDIF
  IF Array[Counter] < MinimumValue THEN
    MinimumValue ← Array[Counter]
  ENDIF
NEXT Counter

Totalling, Counting & Average

Standard loop patterns for accumulation and filtering conditions.

Total ← 0
PassCount ← 0

FOR Counter ← 1 TO NumberOfValues
  Total ← Total + StudentMark[Counter]
  IF StudentMark[Counter] >= 50 THEN
    PassCount ← PassCount + 1
  ENDIF
NEXT Counter

Average ← Total / NumberOfValues
OUTPUT "Total: ", Total
OUTPUT "Average: ", Average
OUTPUT "Passed: ", PassCount

Bubble Sort Algorithm

Sorts an array into ascending order by iteratively comparing adjacent elements and swapping them until fully ordered.

First ← 1
Last ← 10
REPEAT
  Swap ← FALSE
  FOR Index ← First TO Last - 1
    IF Array[Index] > Array[Index + 1] THEN
      Temp ← Array[Index]
      Array[Index] ← Array[Index + 1]
      Array[Index + 1] ← Temp
      Swap ← TRUE
    ENDIF
  NEXT Index
  Last ← Last - 1
UNTIL (NOT Swap) OR Last = 1

Bubble Sort — Interactive Visualizer

Step through or play the trace to watch each comparison, swap, and the pseudocode line update live.

Linear Search

Searches through the array until the target value is found or the end is reached.

INPUT TargetValue
Found ← FALSE
Counter ← 1

REPEAT
  IF TargetValue = Array[Counter] THEN
    Found ← TRUE
  ELSE
    Counter ← Counter + 1
  ENDIF
UNTIL Found OR Counter > NumberOfValues

IF Found THEN
  OUTPUT "Found at position: ", Counter
ELSE
  OUTPUT "Not found."
ENDIF

Linear Search — Interactive Visualizer

Set a target value, then step through or play the trace to watch the pointer scan the array and the pseudocode line update live.

Range & Length Check

Range Check:

REPEAT
  INPUT Mark
  IF Mark < 0 OR Mark > 100 THEN
    OUTPUT "Mark must be between 0 and 100"
  ENDIF
UNTIL Mark >= 0 AND Mark <= 100

Length Check:

REPEAT
  INPUT Password
UNTIL LENGTH(Password) >= 8

Presence, Type, Format & Check Digit

Presence Check – a required field is not left blank:

REPEAT
  INPUT Name
  IF Name = "" THEN
    OUTPUT "This field is required"
  ENDIF
UNTIL Name <> ""

Type Check – data is of the correct data type:

REPEAT
  INPUT Age
  IF Age <> DIV(Age, 1) THEN
    OUTPUT "Please enter a whole number"
  ENDIF
UNTIL Age = DIV(Age, 1)

Format Check – data follows a pre-defined pattern (e.g. DD/MM/YYYY dates, Student ID "S####").

Check Digit – an extra digit calculated from the other digits to detect data entry errors (used in barcodes, ISBNs, VINs):

IF CalculatedCheckDigit <> EnteredCheckDigit THEN
  OUTPUT "Invalid code"
ENDIF

Verification

Verification checks that data has been copied or entered accurately, usually by comparing it with the original source.

Double Entry: The same data is entered twice (often by different operators) and compared.

INPUT Password
INPUT ConfirmPassword
IF Password <> ConfirmPassword THEN
  OUTPUT "Entries do not match"
ENDIF

Visual Check: A person compares the data entered on screen with the original source document.

Types of Test Data

Suppose a program accepts marks from 0 to 100:

TypeMeaningExampleExpected Result
NormalValid, typical data65Accepted
AbnormalInvalid data-10, 120Rejected
ExtremeValid data close to the limits1, 99Accepted
BoundaryData exactly at (or just outside) the limits0, 100 (accepted) • -1, 101 (rejected)See example

Validation vs Verification

AspectValidationVerification
PurposeChecks whether data is reasonable / acceptableChecks whether data was entered / copied accurately
Who performs itUsually performed by the computerCan involve a person, or repeated data entry
MethodsRange, length, presence, type, format, check digitDouble entry, visual check
ExampleMark must be 0–100Checking an entered mark against the original paper

Easy way to remember: Validation = "Is this data acceptable?"  |  Verification = "Did I enter/copy the data correctly?"

1D Arrays (Declaration & Iteration)

// Declaration: 1D Array of size 10
DECLARE StudentNames : ARRAY[1:10] OF STRING
DECLARE Scores : ARRAY[1:10] OF INTEGER

// Populating array
FOR Index ← 1 TO 10
  INPUT StudentNames[Index]
  INPUT Scores[Index]
NEXT Index

// Accessing Nth element
OUTPUT "First student is: ", StudentNames[1]

2D Arrays (Nested Loops)

// Declaration: 2D Array (e.g. 5 rows, 10 columns)
DECLARE Amount : ARRAY[1:5, 1:10] OF INTEGER
DECLARE GrandTotal : INTEGER
GrandTotal ← 0

FOR Row ← 1 TO 5
  RowTotal ← 0
  FOR Column ← 1 TO 10
    RowTotal ← RowTotal + Amount[Row, Column]
  NEXT Column
  OUTPUT "Total for Row ", Row, " is ", RowTotal
  GrandTotal ← GrandTotal + RowTotal
NEXT Row

OUTPUT "Grand Total: ", GrandTotal

String Handling Functions

LENGTH(string)

DECLARE Name : STRING
Name ← "Computer Science"
OUTPUT LENGTH(Name) // Outputs 16

SUBSTRING(string, start, length)

// SUBSTRING(str, pos, count)
OUTPUT SUBSTRING("Computer Science", 10, 7)
// Outputs "Science"

UCASE(string) & LCASE(string)

OUTPUT UCASE("hello") // Outputs "HELLO"
OUTPUT LCASE("WORLD") // Outputs "world"

File Handling Modes

  • READ: Opens file for data retrieval from the beginning.
  • WRITE: Creates a new file or overwrites an existing file.
  • APPEND: Adds new data to the end of an existing file.

Writing to a Text File

OPENFILE "StudentData.txt" FOR WRITE
WRITEFILE "StudentData.txt", "Bob, Smith, 90"
WRITEFILE "StudentData.txt", "Ada, Lovelace, 100"
CLOSEFILE "StudentData.txt"

Reading Lines from File until EOF

Reads every line of a text file sequentially until EOF (End Of File) is reached.

DECLARE LineOfText : STRING

OPENFILE "StudentData.txt" FOR READ

WHILE NOT EOF("StudentData.txt") DO
  READFILE "StudentData.txt", LineOfText
  OUTPUT LineOfText
ENDWHILE

CLOSEFILE "StudentData.txt"

Standard Flowchart Symbols

Symbol Name Function
START
Terminator Shows the start and end termination points of an algorithm.
Process
Process Calculations, data assignments, and internal tasks.
Input/Output
Input / Output Prompts input from keyboard or prints output to monitor.
Decision Conditional branching check with Yes/No exit paths.
→
Flowline Defines directional sequence of execution.

Worked Example: Odd or Even Number

Flowchart equivalent of: IF Num MOD 2 = 0 THEN OUTPUT "Even" ELSE OUTPUT "Odd" ENDIF

START INPUT Num Num MOD 2 = 0 ? YES OUTPUT "Even" NO OUTPUT "Odd" END

Trace Tables

A trace table follows the values of variables through a program, one instruction at a time, to check whether an algorithm produces the correct result.

Total ← 0
FOR Count ← 1 TO 3
  INPUT Number
  Total ← Total + Number
NEXT Count
OUTPUT Total

Input values: 5, 7, 3

StepCountNumberTotalAction
1--0Initial values
2155Total ← Total + Number
32712Total ← Total + Number
43315Total ← Total + Number
---15Output Total (final output: 15)

How to trace: (1) Start with initial values • (2) Execute each instruction in order • (3) Record changes to variables • (4) Continue until the algorithm finishes • (5) Check the final output against the expected result.

Chapter 8 - Programming

This section (translating pseudocode into an actual programming language, e.g. Python) hasn't been added yet. Let me know the topics or examples you'd like here and I'll fill this tab in.

Relational Concepts

  • Flat File: Single table containing all data.
  • Relational Database: Multiple linked tables reducing redundancy.
  • Primary Key: Unique identifier field for a record.
  • Foreign Key: Links to another table's primary key.

Standard Query (SELECT)

SELECT Forename, Lastname
FROM Students
WHERE StudentID < 10
ORDER BY Lastname ASC;

Modifying Tables (SQL)

INSERT

INSERT INTO Students (ID, Name)
VALUES (1, 'Adam');

UPDATE

UPDATE Students
SET Class = '11A'
WHERE StudentID = 1;

DELETE

DELETE FROM Students
WHERE StudentID = 1;

AND Gate

OUT = A AND B

Output 1 only when all inputs are 1.

XYOUT
000
010
100
111

NAND Gate

OUT = NOT (A AND B)

Opposite of AND. Output is 0 only when both inputs are 1.

XYOUT
001
011
101
110

OR Gate

OUT = A OR B

Output is 1 if at least one input is 1.

XYOUT
000
011
101
111

NOR Gate

OUT = NOT (A OR B)

Opposite of OR. Output is 1 only when both inputs are 0.

XYOUT
001
010
100
110

XOR Gate

OUT = A XOR B

Output 1 only when inputs are different.

XYOUT
000
011
101
110

XNOR Gate

OUT = NOT (A XOR B)

Output 1 when both inputs are identical.

XYOUT
001
010
100
111

NOT Gate

OUT = NOT A

Inverts input (1 becomes 0, 0 becomes 1).

XOUT
01
10