8.1 Programming

Declarations and Data Types

1. Data Types

Every piece of data must have a type. This tells the computer how much memory to allocate and what operations are possible.

INTEGER: Whole numbers (e.g., 10, -5).
REAL: Numbers with decimals (e.g., 15.50, -0.5).
CHAR: A single character (e.g., 'A', '$').
STRING: Text (e.g., "Hello World").
BOOLEAN: Logic values (TRUE or FALSE).

2. Variables, Constants, and Assignment

  • Variable: A named memory location where the value can change during program execution.
  • Constant: A value that remains fixed throughout the program (e.g., PI).
DECLARE StudentName : STRING
DECLARE StudentAge : INTEGER
CONSTANT Discount = 0.10

// Use the assignment arrow ← (not =)
StudentName ← "John Doe"
StudentAge ← 16

3. Arrays (1D and 2D)

Arrays store multiple items of the same data type under one name using an index.

// 1D Array: List of 10 student names
DECLARE Names : ARRAY[1:10] OF STRING
Names[1] ← "Alice"

// 2D Array: Grid (e.g., 3 students, 4 marks each)
DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER
Marks[1, 1] ← 85

4. Operators

Type Operators Notes
Arithmetic + , - , * , / Standard math operations.
Comparison = , <> , < , > , <= , >= Note: <> means "Not Equal To".
Logical AND , OR , NOT Used to combine Boolean conditions.
Integer Math DIV , MOD DIV is whole quotient; MOD is remainder.

5. Library Routines

Common built-in functions you are expected to use in IGCSE pseudocode:

  • LENGTH(String): Returns the number of characters.
  • SUBSTRING(String, Start, Length): Extracts a part of a string.
  • ROUND(Number, Decimals): Rounds to specified decimal places.
  • UPPER(String) / LOWER(String): Changes text case.

6. Procedures and Functions (Subroutines)

A procedure performs a task. A function performs a task and returns a value.

// Procedure with 2 parameters
PROCEDURE CalculateArea(Length : REAL, Width : REAL)
  OUTPUT Length * Width
ENDPROCEDURE

// Function with 2 parameters
FUNCTION FindMax(Num1 : INTEGER, Num2 : INTEGER) RETURNS INTEGER
  IF Num1 > Num2 THEN
    RETURN Num1
  ELSE
    RETURN Num2
  ENDIF
ENDFUNCTION
⚠️ Exam Note: In pseudocode, always use the Left Arrow for assignment. Do not use = for assignment; = is only used for comparing values (e.g., in an IF statement).

Basic Constructs

1. Selection

Selection allows the program to choose different paths based on a condition.

IF ... THEN ... ELSE

Used for binary choices (Yes/No).

IF Mark >= 50 THEN
  OUTPUT "Pass"
ELSE
  OUTPUT "Fail"
ENDIF
CASE ... OF

Efficient for multiple discrete choices (e.g., a menu).

CASE Choice OF
  1 : CALL AddRecord()
  2 : CALL DeleteRecord()
  3 : CALL ViewRecord()
  OTHERWISE OUTPUT "Invalid Choice"
ENDCASE

2. Iteration (Loops)

Iteration is used to repeat a block of code multiple times.

FOR ... TO ... NEXT

Count-controlled: Used when you know exactly how many times the loop should run.

FOR Count ← 1 TO 10
  OUTPUT "Iteration: ", Count
NEXT Count
REPEAT ... UNTIL

Post-condition: The condition is checked at the end. The loop always runs at least once.

REPEAT
  OUTPUT "Enter a positive number"
  INPUT Num
UNTIL Num > 0
WHILE ... DO ... ENDWHILE

Pre-condition: The condition is checked at the start. If the condition is false initially, the loop never runs.

WHILE Answer <> "Exit" DO
  INPUT Answer
ENDWHILE

3. Comparison Table: Which Loop to Use?

Loop Type Best Used For... Min. Iterations
FOR Fixed number of repetitions. Defined by range
REPEAT Validation (checking input). 1
WHILE Reading files or unknown repetitions. 0
⚠️ Exam Note: Make sure to close your constructs! Every IF needs an ENDIF, every WHILE needs an ENDWHILE, and every CASE needs an ENDCASE.

File Handling

WHY USE FILES?

In your Python programs, variables are stored in RAM (Temporary). When you close the program, the data is gone. Files allow us to store data in Secondary Storage (Permanent) so we can load it again later.

1. The 3 Steps of File Handling

  1. Open the file: Tell the computer which file you want and if you want to Read (r) or Write (w).
  2. Process: Read data from the file or write data into it.
  3. Close the file: Very important! This saves your changes and frees up memory.

2. Python Examples for IGCSE

A. Writing to a File

# This creates a file called 'names.txt' file = open("names.txt", "w") file.write("Alice\n") file.write("Bob\n") file.close() # Always close your file!

B. Reading from a File

# Opens the file in 'read' mode file = open("names.txt", "r") for line in file: print(line.strip()) # .strip() removes the extra newline file.close()
📝 IGCSE Exam Tip:

You might be asked: "What happens if you open a file for writing ('w') that already has data in it?"
Answer: The old data is deleted (overwritten). To keep old data, use append ('a').

Ready for the next IGCSE topic: Logic Gates or Input/Output Devices?

Library Routines & Operators

1. The Three Categories of Operators

A. Arithmetic Operators

These are used to perform mathematical calculations on numerical data types (Integer and Real).

OperatorFunctionExample
+Addition10 + 5 = 15
-Subtraction10 - 5 = 5
*Multiplication10 * 5 = 50
/Division10 / 4 = 2.5
DIVInteger Division (Quotient only)10 DIV 4 = 2
MODModulo (Remainder only)10 MOD 4 = 2

B. Relational (Comparison) Operators

These compare two values and return a Boolean result (TRUE or FALSE). Used in IF statements and Loops.

OperatorFunctionExample
=Equal toX = 10
<>Not equal toX <> 10
>Greater thanX > 10
<Less thanX < 10
>=Greater than or equal toX >= 10
<=Less than or equal toX <= 10

C. Boolean (Logical) Operators

Used to combine multiple conditions together to form complex logic.

OperatorFunctionExample
ANDTrue only if BOTH are true(X > 5) AND (X < 10)
ORTrue if AT LEAST ONE is true(Ans = 'Y') OR (Ans = 'y')
NOTReverses the Boolean valueNOT (X = 10)

2. Official Library Routines (String Handling)

The following are the only string functions recognized in the Cambridge marking schemes:

RoutineFunction
LENGTH(String)Returns the length of the string as an integer.
LCASE(String)Converts all characters to lowercase.
UCASE(String)Converts all characters to uppercase.
SUBSTRING(s, start, length)Extracts a portion of string s starting at start for length.
LEFT(String, n)Returns the first n characters of the string.
RIGHT(String, n)Returns the last n characters of the string.
// Example usage in an algorithm DECLARE MyText : STRING MyText "Cambridge" OUTPUT LENGTH(MyText) // Result: 9 OUTPUT SUBSTRING(MyText, 1, 3) // Result: "Cam"

3. Numeric & Random Routines

RoutineFunction
INT(n)Returns the integer part of value n.
ROUND(n, d)Rounds n to d decimal places.
RANDOM()Returns a random real number between 0 and 1 inclusive.
📝 Exam Note (Very Important):

In Cambridge pseudocode, the Assignment Operator is an arrow: .
Using a single equals sign (=) for assignment is a common mistake; it should only be used for comparison.

Worked Examples

Example 1: Temperature Monitoring System

The Scenario: A greenhouse requires a program to record 24 hourly temperature readings. The program must:
  • Store the readings in a 1D array.
  • Calculate and output the average temperature.
  • Identify and output the highest and lowest temperatures recorded.
DECLARE Temp : ARRAY[1:24] OF REAL
DECLARE Total, Average, Max, Min : REAL
DECLARE i : INTEGER

Total ← 0

// 1. Input loop with Validation
FOR i ← 1 TO 24
  REPEAT
    OUTPUT "Enter temperature for hour ", i
    INPUT Temp[i]
  UNTIL Temp[i] > -50 AND Temp[i] < 60
  Total ← Total + Temp[i]
NEXT i

// 2. Initialize Max and Min with the first value in the array
Max ← Temp[1]
Min ← Temp[1]

// 3. Search Loop
FOR i ← 2 TO 24
  IF Temp[i] > Max THEN Max ← Temp[i] ENDIF
  IF Temp[i] < Min THEN Min ← Temp[i] ENDIF
NEXT i

Average ← Total / 24

OUTPUT "Average: ", Average
OUTPUT "Highest: ", Max, " Lowest: ", Min

Example 2: School Grades (2D Arrays)

The Scenario: A teacher manages marks for 30 students across 3 subjects (Maths, Science, English). The program must:
  • Use a 2D array to store the marks.
  • Count how many students scored an average of > 80 (Distinction).
  • Allow a teacher to search for a student's marks by entering their ID (1-30).
DECLARE Marks : ARRAY[1:30, 1:3] OF INTEGER
DECLARE StudentID, DistCount, Row, Col : INTEGER
DECLARE StudentSum : REAL

DistCount ← 0

// Populate the 2D Array
FOR Row ← 1 TO 30
  StudentSum ← 0
  FOR Col ← 1 TO 3
    INPUT Marks[Row, Col]
    StudentSum ← StudentSum + Marks[Row, Col]
  NEXT Col

  // Check for Distinction
  IF (StudentSum / 3) > 80 THEN
    DistCount ← DistCount + 1
  ENDIF
NEXT Row

// Search Functionality
OUTPUT "Enter Student ID (1-30):"
INPUT StudentID
OUTPUT "Maths: ", Marks[StudentID, 1]
OUTPUT "Science: ", Marks[StudentID, 2]
OUTPUT "English: ", Marks[StudentID, 3]
OUTPUT "Total distinctions: ", DistCount
15-Mark Strategy Checklist
  • Initialization: Did you set totals to 0 and max/min variables?
  • Input Prompts: Did you use OUTPUT before every INPUT?
  • Validation: Did you use REPEAT...UNTIL for range checks?
  • End Tags: Did you close every FOR, IF, and WHILE?
  • Efficiency: Did you use the correct data types (REAL for averages)?