Programming 💻
From pseudocode to real code: variables, data types, loops, strings, procedures, functions, arrays and files — side by side in pseudocode, Python, Visual Basic and Java, with a live interpreter that shows memory, the call stack and files as your program runs.
🗣️ One idea, many languages 8.1
An algorithm written in pseudocode becomes a program when it's written in a real high-level language, translated, and run — and once there are no syntax errors, the computer does exactly what you wrote. For IGCSE the recommended languages are Python (general purpose, open source, very readable), Visual Basic (widely used on Windows) and Java (a commercial language used by many developers). Each is written in an IDE — Python's IDLE, Visual Studio, BlueJ — free to download.
Pick your language — every code box on this page switches to it (you can still flip any single box):
Same output, very different code: Visual Basic needs a Module with a Sub Main(), Java needs a class (named like the file) with a main method and a ; after every statement, Python needs one line.
🧩 The five basic constructs 8.1
- 📦 Data use — variables, constants and arrays
- ➡️ Sequence — the order of the steps
- 🔀 Selection — choosing a path through the program
- 🔁 Iteration — repeating a sequence of steps
- ➕ Operator use — arithmetic for calculations; logical and Boolean for decisions
📦 Variables and constants 8.1.1
Give both meaningful names so other people can understand the program. Constants are often shown with capitals (PI) or a prefix (ConstPi). It's good practice to declare them — state their name and data type — at the start of the program or just before first use. Some languages need explicit declarations (VB, Java); others use implicit declarations where the type comes from the value assigned (Python).
Python doesn't separate constants from variables — the programmer must keep track. Java makes a constant with final so it can never be changed.
🏷️ Basic data types 8.1.2
Giving data a type lets it be stored in the right way, manipulated properly (maths on numbers, joining on characters) and sometimes validated automatically.
| Pseudocode | What it holds | Examples | Python | Visual Basic | Java |
|---|---|---|---|---|---|
| INTEGER | A positive or negative whole number | 25, −3, 0 | int | Integer | int / byte |
| REAL | A number with a fractional part | 25.0, 3.142 | float | Decimal | float / double |
| CHAR | A single character | 'F', '?' | str (length 1) | Char | char |
| STRING | Several characters — maybe none (an empty string) | "Emma", "" | str | String | String |
| BOOLEAN | Only TRUE or FALSE | TRUE | bool | Boolean | boolean |
⌨️ Input and output 8.1.3
Every input needs a prompt so the user knows what to type, and every output needs a message explaining the result. Inputs arrive as strings, so a number must be converted — this is called casting (int()/float() in Python, Decimal.Parse() in VB; Java's Scanner reads the type directly).
Input with a prompt
Output with a message
The separator differs: Python uses ,, VB uses &, Java uses +.
🔎 Data-type detective
Type a value as a user would. See its data type and how each language would store it — then see why casting matters.
🧪 The casting trap: what does + do?
🛢️ A complete program: volume of a cylinder 8.1.3
Constant, variables, prompted inputs with casting, a calculation and a labelled output — everything so far in one program:
➡️ Sequence 8.1.4(a)
The order of the steps matters. A wrong order gives wrong results and can add steps the task doesn't need. A classic: adding marks until a rogue value (999) is typed. If the 999 is added to the total and counted before the loop ends, every output is wrong. Moving the input to after the addition, starting the counter at −1, and working out the average once, after the loop, fixes all three.
Load both versions into the runner below with test data 25, 27, 23, 999 and compare the trace tables.
💻 Pseudocode runner — sequence, selection and loops
Pick a program or write your own, type the test data (separated by commas), then Run or Step one line at a time. The trace table and memory fill in as it runs.
🔀 Selection: IF 8.1.4(b)
Selection lets a program take different routes — pick out the largest value, items over a price, everyone in a group. Python has no THEN or ENDIF, just a colon and indentation; VB uses Then … End If; Java uses .
🎛️ Selection: CASE 8.1.4(b)
CASE handles many choices on one value. Python uses if … elif … else (or match in Python 3.10+), VB uses Select Case … Case Else, Java uses switch with default — and needs break to stop each case running into the next.
🔁 Iteration: three kinds of loop 8.1.4(c)
Count-controlled (FOR)
A set number of iterations. Counting from 1 to 10 in steps of 2 — notice Python's range stops before its end value, so it's 11:
Pre-condition (WHILE)
The condition is tested first, so it may run zero times:
Post-condition (REPEAT)
Tested at the end, so it always runs at least once. Python only has pre-condition loops; Java's do … while keeps going while the condition is true — the opposite of UNTIL:
➕ Totalling and counting 8.1.4(d)
Totalling keeps a running total that values are added to; counting keeps track of how many times something happens. Totalling looks the same in all three languages; Java has a shortcut for counting:
🔤 String handling 8.1.4(e)
A string holds text, from the empty string up to a maximum length set by the language. Each character has a position number — and here's the trap: pseudocode strings start at position 1, but Python, VB and Java start at 0. You need four methods (usually provided as library routines):
- 📏 length — the number of characters ("Computer Science" is 16: the space counts)
- ✂️ substring — extract part of a string, e.g. "Science"
- 🔠 upper — "COMPUTER SCIENCE" · lower — "computer science"
Read the substring parameters carefully: pseudocode and VB take (start, length); Python slices take [start : end]; Java's substring(start, end) has an exclusive end — the position after the last character.
✂️ String lab — positions from 1 or from 0
Choose the start position and length. The top number on each character is its pseudocode position; the bottom one is its index in Python, VB and Java.
🧮 Arithmetic, logical and Boolean operators 8.1.4(f)
| Operator | Action | Python | Visual Basic | Java |
|---|---|---|---|---|
| + − * / | Add, subtract, multiply, divide | + - * / | + - * / | + - * / |
| ^ | Raise to the power of | ** | ^ | Math.pow(x, y) |
| MOD | Remainder of a division | % | Mod | % |
| DIV | Integer (whole-number) division | // | \ | / (with two integers) |
Logical (comparison) operators
| Meaning | Pseudocode | Python | VB | Java |
|---|---|---|---|---|
| Greater / less than | > < | > < | > < | > < |
| Equal | = | == | = | == |
| ≥ and ≤ | >= <= | >= <= | >= <= | >= <= |
| Not equal | <> | != | <> | != |
Boolean operators
| Operator | True when… | Python | VB | Java |
|---|---|---|---|---|
| AND | both are true | and | And | && |
| OR | either is true | or | Or | || |
| NOT | it is not true | not | Not | ! |
Group expressions with brackets to make the order clear, e.g. ((X + Y) * 3) / PI. Logical operators decide the path through a program; Boolean operators combine them into bigger conditions:
🧮 Operator lab
Enter two numbers — every operator is worked out by the pseudocode interpreter, with the symbol each language uses.
🪆 Nested statements 8.1.5
One construct can sit inside another — selection inside a loop, a loop inside a loop. Nesting cuts down the code you write and makes it easier to test. A big example: highest, lowest and average marks for each subject (5 tests), each student (6 subjects) and the whole class (20 students) needs three nested loops:
FOR Student ← 1 TO ClassSize // outer loop // set StudentHigh ← 0, StudentLow ← 100, StudentTotal ← 0 FOR Subject ← 1 TO NumberOfSubjects // middle loop // set SubjectHigh ← 0, SubjectLow ← 100, SubjectTotal ← 0 FOR Test ← 1 TO NumberOfTests // inner loop INPUT Mark // update SubjectHigh, SubjectLow, SubjectTotal NEXT Test // output the subject results; update the student results NEXT Subject // output the student results; update the class results NEXT Student // output the class results
Using constants for ClassSize, NumberOfSubjects and NumberOfTests means you can shrink them to 2 or 3 for testing by changing one line each. Build it inside-out: get the inner loop working first (Activity 8.11), then wrap the middle loop around it (8.12), then the outer loop (8.13).
💻 Pseudocode runner — strings, operators and nesting
The whole-class program is here, shrunk to 2 students × 2 subjects × 2 tests so the trace table stays readable.
🧩 Procedures, functions and parameters 8.1.6
When the same group of statements is needed again and again, write it once as a subroutine and call it whenever it's needed.
Names differ by language: a procedure is a void function in Python, a Sub (subroutine) in VB and a method in Java; a function is a fruitful function in Python, a Function in VB and a method with a return in Java.
A procedure without parameters
🎚️ Passing a parameter 8.1.6
An argument changes what the procedure does — here, how many stars it outputs. The call must match the definition: the same number of arguments as parameters, in the same order, of the right types. (For IGCSE, at most two parameters.)
Call it with a value, CALL Stars(7), or with a variable, MyNumber ← 7 then CALL Stars(MyNumber) — the value 7 is copied into the parameter Number.
↩️ Functions return a value 8.1.6
RETURN gives back the value — usually the last statement. Both the parameter and the return value have data types in the header. Because a function produces a value, its call goes in an expression, on the right-hand side: MyTemp ← Celsius(MyTemp). A procedure call is a standalone statement.
The header (first line) of a procedure or function contains its name, any parameters and their data types, and — for a function — the data type of the return value.
💻 Pseudocode runner — with the call stack
Step through a CALL: a yellow box appears for the procedure's local variables and parameters, and disappears when it ends. Globals stay in the blue box the whole time.
🌍 Local and global variables 8.1.6
In this program the main program's Number1, Number2 and Answer are global. The procedure declares its own local Number1, Number2, Number3 and Answer — so changing them inside Test doesn't touch the globals, and the main program can't see Number3 at all:
Output: the main program shows 50, 100 and 150; Test shows 10, 20 and 30; back in the main program they're still 50, 100 and 150; the last line is an error — Number3 is undefined there. Load "Local and global variables" into the runner above and step through it.
📚 Library routines 8.1.7
An IDE comes with a standard library of ready-made, fully tested functions and procedures, like the string handling routines. In Java some must be imported first (import java.lang.String;). You need these four:
- ➗ MOD — the remainder of a division · DIV — the quotient (whole-number part)
- 🎯 ROUND — a value rounded to a given number of decimal places
- 🎲 RANDOM — a random number between 0 and 1
Python's divmod(x, y) gives both answers at once (DIV first, then MOD). Java's Math.round only rounds to a whole number — multiply by 100, round, divide by 100.0 for 2 decimal places.
🛠️ Creating a maintainable program 8.1.8
Programs are often updated later by someone else — who may have nothing but the source code. (Even you, years later, will have forgotten how it works!) A maintainable program:
- 🏷️ uses meaningful identifiers for variables, constants, arrays, procedures and functions
- 🧩 is divided into modules — procedures and functions — one for each task
- 💬 is fully commented using the language's comment feature
🗃️ Arrays 8.2
Arrays let you store, search and sort lists (names in alphabetical order, temperatures to search). The first index can be 0 or 1, but most languages start at 0. A one-dimensional array is a list. When it's declared in pseudocode, give its name, first index, last index and data type:
DECLARE MyList : ARRAY[0:9] OF INTEGER MyList[4] ← 27 // store 27 at index 4 — the FIFTH element OUTPUT MyList[1] // display the element at index 1
Fill a whole array with a loop, using the loop counter as the index:
🧊 3D · Arrays in memory
Each element is a memory location with the same name and its own index. Press Populate to watch the FOR loop INPUT each value into place, then OUTPUT any element by its index. Switch to the 2D table and compare the two orders of nested loops. Drag to rotate.
🔲 Two-dimensional arrays 8.2
A two-dimensional array is a table of rows and columns. MyTable has 10 rows and 3 columns — 30 elements — and its first element is at [0, 0]. The declaration gives the first and last row index, the first and last column index, and the data type. Populating it needs two nested loops, one for each index:
| Row | Col 0 | Col 1 | Col 2 |
|---|
OUTPUT MyTable[2, 1] displays 98 — row 2, column 1. Python has lists instead of arrays (a list can mix data types); a table is a list of lists, indexed MyTable[2][1].
📄 File handling 8.3
Data in RAM is lost when the computer is switched off. Saving it to a file stores it permanently, so it can be used again later by the same program, by a different program, or sent to other computers. Every file is identified by its filename. The steps are always: open it (for READ, WRITE or APPEND), read or write a line, and close it.
You'll see two pseudocode styles: OPEN MyFile FOR WRITE with WRITEFILE, TextLine, and the Cambridge syllabus form OPENFILE MyFile FOR WRITE with WRITEFILE MyFile, TextLine. The runner accepts both.
💻 Pseudocode runner — arrays and files
Files live in the panel on the right: watch lines appear as they're written, and the read position move as they're read.
✏️ Practice hub 26 activities · every example
Every activity from the coursebook chapter — auto-marked where there's a single right answer (many checked by the pseudocode interpreter itself), with model programs in pseudocode, Python, Visual Basic and Java for the writing tasks. Fresh questions every time you hit 🔀 New questions.
📘 Worked examples
Every type of worked example in the chapter, step by step. Hit 🔀 Another example for a new one.
🃏 Key-term flashcards Tap to flip
🧠 Mini-quiz
📝 Exam-style questions Try, then peek
- ✅ Both are named data stores that hold a value, and both should have meaningful names and a data type.
- ✅ A variable’s value can change while the program runs; a constant’s value cannot.
- ✅ Constants are often written in capitals (or declared with final / Const) so they stand out.
- ✅ A constant means a fixed value (e.g. a tax rate) only needs changing in one place.
- ✅ ItemName — STRING · Manufacturer — STRING · Description — STRING
- ✅ NumberInStock — INTEGER · ReorderLevel — INTEGER
- ✅ OnOrder — BOOLEAN
- ✅ Sequence — steps run in order; the order affects the result: INPUT A then B ← A * 2.
- ✅ Selection — choosing a path with IF or CASE: IF Age > 17 THEN OUTPUT "Adult" ENDIF.
- ✅ Iteration — repeating steps with FOR, REPEAT or WHILE: FOR I ← 1 TO 10 … NEXT I.
- ✅ Totalling — adding each value to a running total: Total ← Total + Mark.
- ✅ Counting — adding 1 each time something happens: Count ← Count + 1.
OUTPUT "Please enter your password "
INPUT Password
IF LENGTH(Password) = 8 AND Password = UCASE(Password)
THEN
OUTPUT "Password meets the rules"
ELSE
OUTPUT "Password must be 8 characters, all letters in upper case"
ENDIFIf the password has any lower-case letters, UCASE changes it, so it’s no longer equal to the original.
- ✅ A global variable is declared in the main program and can be used anywhere — its scope is the whole program, e.g. a running ClassTotal.
- ✅ A local variable is declared inside a procedure or function and can only be used there, e.g. a loop Counter inside PROCEDURE Stars.
- ✅ A local variable exists only while its subroutine runs; using it outside gives an error (“undefined”).
- ✅ A local can have the same name as a global without changing it; locals make modules independent and easier to test and reuse.
- ✅ They are already written and fully tested, so they save development time and are reliable.
- ✅ The programmer doesn’t need to know how they work, only how to call them.
- ✅ Examples: ROUND (round to a number of decimal places), RANDOM (random number), MOD/DIV, LENGTH, UCASE.
// (b) bubble sort on the family name, swapping whole rows
Last ← 10
REPEAT
Swapped ← FALSE
FOR Row ← 1 TO Last - 1
IF Names[Row, 2] > Names[Row + 1, 2]
THEN
FOR Column ← 1 TO 2
Temp ← Names[Row, Column]
Names[Row, Column] ← Names[Row + 1, Column]
Names[Row + 1, Column] ← Temp
NEXT Column
Swapped ← TRUE
ENDIF
NEXT Row
Last ← Last - 1
UNTIL NOT Swapped OR Last = 1
// (a) display the names
FOR Row ← 1 TO 10
OUTPUT Names[Row, 1], " ", Names[Row, 2]
NEXT RowOPENFILE "Message.txt" FOR READ READFILE "Message.txt", LineOfText OUTPUT LineOfText CLOSEFILE "Message.txt"
- ✅ (a) The loop repeats 300 times; each time a name is input and stored in the next element of the array Name, from Name[1] to Name[300].
- ✅ (b) A REPEAT … UNTIL loop (or WHILE … DO … ENDWHILE) with a counter I starting at 1, adding 1 each time, until I > 300.
OUTPUT "Please enter a number from 0 to 100 "
INPUT Number
IF Number < 0 OR Number > 100
THEN
OUTPUT "Error: the number must be from 0 to 100"
ENDIF🚀 Challenge projects Beyond the activities
- 📞 Staff directory. Three parallel arrays StaffName, StaffPhone and StaffOffice. Write procedures to list phone numbers in alphabetical order of name, list staff grouped by office, show everything for one member of staff (name as a parameter) and update their details. Use local and global variables, comments — then test it with a trace table.
- 🏛️ Town guild membership. Ask questions about age (18–65), years lived in town and family, savings, a clean record and supporters. Issue a unique membership number if every rule is met, or list every reason for failure if not — remembering that five supporters can excuse one rule (except age).