Skip to content
Pseudocode Converter

Java → Cambridge A Level Pseudocode

Cambridge International AS & A Level 9618

Key rules

  1. 01Like IGCSE: DECLARE with types, PascalCase names, arrays declared ARRAY[0:n] (0-based kept).
  2. 02IF condition THEN is written on one line; WHILE condition has no DO.
  3. 03Integer division and remainder are operators: a DIV b, a MOD b.
  4. 04Strings are joined with &, and parts of a string are taken with MID(s, start, length).
  5. 05A procedure that changes an array it is given receives it BYREF.
Contents10 sections
  1. —Quick reference
  2. 01Basics
  3. 02Operators
  4. 03Selection
  5. 04Loops
  6. 05Arrays & lists
  7. 06Strings
  8. 07Subprograms
  9. 08Random numbers
  10. 09Complete programs

Quick reference

ConceptJavaA Level
Assignment
int x = 5;
DECLARE X : INTEGERX ← 5
Output
System.out.println("Hi");
OUTPUT "Hi"
Input
String name = sc.nextLine();
INPUT Name
If
if (x > 3) {    System.out.println(x);}
IF X > 3 THEN   OUTPUT XENDIF
Else if
if (x > 3) {    System.out.println(1);} else if (x > 1) {    System.out.println(2);}
IF X > 3 THEN   OUTPUT 1ELSE   IF X > 1 THEN      OUTPUT 2   ENDIFENDIF
While loop
while (x < 3) {    x = x + 1;}
WHILE X < 3   X ← X + 1ENDWHILE
Counting loop
for (int i = 0; i < 5; i++) {    System.out.println(i);}
DECLARE I : INTEGERFOR I ← 0 TO 4   OUTPUT INEXT I
Repeat n times
for (int i = 0; i < 3; i++) {    System.out.println("Hi");}
DECLARE I : INTEGERFOR I ← 0 TO 2   OUTPUT "Hi"NEXT I
For each
for (int x : xs) {    System.out.println(x);}
FOR I ← 0 TO 1   X ← Xs[I]   OUTPUT XNEXT I
Create array
int[] xs = {4, 7, 9};
DECLARE Xs : ARRAY[0:2] OF INTEGERXs[0] ← 4Xs[1] ← 7Xs[2] ← 9
Array access
System.out.println(xs[0]);
OUTPUT Xs[0]
Length
System.out.println(xs.length);
OUTPUT 3
Function + return
static int twice(int n) {    return n * 2;}// in main:System.out.println(twice(4));
FUNCTION Twice(N : INTEGER) RETURNS INTEGER   RETURN N * 2ENDFUNCTIONOUTPUT Twice(4)
Procedure + call
static void show(int n) {    System.out.println(n);}// in main:show(3);
PROCEDURE Show(N : INTEGER)   OUTPUT NENDPROCEDURECALL Show(3)
Integer division
int b = a / 2;
B ← A DIV 2
Remainder
int b = a % 2;
B ← A MOD 2
Not equal
System.out.println(a != 2);
OUTPUT A <> 2
And / or / not
System.out.println(a && !b || b);
OUTPUT A AND NOT B OR B
String join
String t = s + "cd";
T ← S & "cd"
Random 1–6
int r = rand.nextInt(6) + 1;
R ← INT(RAND(6)) + 1

01Basics

Cambridge pseudocode is strongly typed: each variable is declared once at the top with DECLARE Name : TYPE before it is used. The converter works out the type (INTEGER, REAL, STRING, BOOLEAN) from your code and writes names in PascalCase.

Examples8

1.1

Comment

Comments start with // in every standard. Write them before the line they explain.

Java
// Calculate the area of a rectangleint area = 4 * 3;
A Level
DECLARE Area : INTEGER// Calculate the area of a rectangleArea ← 4 * 3

1.2

Assign a variable

Cambridge uses ← for assignment and declares the variable with its type first.

Java
int score = 0;score = score + 10;
A Level
DECLARE Score : INTEGERScore ← 0Score ← Score + 10

1.3

Variables of different types

The four basic Cambridge types are INTEGER, REAL, STRING and BOOLEAN. Boolean values are written TRUE / FALSE.

Java
int count = 5;double price = 2.75;String name = "Ana";boolean found = false;
A Level
DECLARE Count : INTEGERDECLARE Price : REALDECLARE Name : STRINGDECLARE Found : BOOLEANCount ← 5Price ← 2.75Name ← "Ana"Found ← FALSE

1.4

Constant

Cambridge has a real CONSTANT Name ← value statement. A name in capitals (or Java final) becomes a CONSTANT.

Java
final int MAX_SIZE = 50;System.out.println(MAX_SIZE);
A Level
CONSTANT MaxSize = 50OUTPUT MaxSize

1.5

Output a value

Printing becomes OUTPUT.

Java
int total = 42;System.out.println(total);
A Level
DECLARE Total : INTEGERTotal ← 42OUTPUT Total

1.6

Output text and a value

OUTPUT takes a comma-separated list, so text and values are separated by commas.

Java
int age = 16;System.out.println("Age: " + age);
A Level
DECLARE Age : INTEGERAge ← 16OUTPUT "Age: ", Age

1.7

Input text

A prompt becomes its own OUTPUT line, followed by INPUT Name. The variable still needs a DECLARE.

Java
Scanner sc = new Scanner(System.in);System.out.print("Enter your name: ");String name = sc.nextLine();System.out.println("Hello " + name);
A Level
DECLARE Name : STRINGOUTPUT "Enter your name: "INPUT NameOUTPUT "Hello ", Name

1.8

Input a number

int() (or sc.nextInt()) is not written, but it tells the converter to DECLARE the variable as INTEGER.

Java
Scanner sc = new Scanner(System.in);System.out.print("Enter your age: ");int age = sc.nextInt();System.out.println(age + 1);
A Level
DECLARE Age : INTEGEROUTPUT "Enter your age: "INPUT AgeOUTPUT Age + 1

Exercises1

Q1.Ask for the user's name and favourite number, then print a message with both.

Scanner sc = new Scanner(System.in);System.out.print("Name: ");String name = sc.nextLine();System.out.print("Favourite number: ");int number = sc.nextInt();System.out.println(name + " " + number);
Show answer
Answer
DECLARE Name : STRINGDECLARE Number : INTEGEROUTPUT "Name: "INPUT NameOUTPUT "Favourite number: "INPUT NumberOUTPUT Name, " ", Number

02Operators

A Level writes integer division and remainder as operators: a DIV b and a MOD b. Not-equal is <> and strings are joined with &.

Examples7

2.1

Arithmetic

+ - * / are the same in every standard. / always gives a real (decimal) result.

Java
double a = 7;double b = 2;System.out.println(a + b);System.out.println(a - b);System.out.println(a * b);System.out.println(a / b);
A Level
DECLARE A : REALDECLARE B : REALA ← 7B ← 2OUTPUT A + BOUTPUT A - BOUTPUT A * BOUTPUT A / B

2.2

Integer division

Integer division is the operator a DIV b. Java / between two ints is also integer division.

Java
int minutes = 135;int hours = minutes / 60;System.out.println(hours);
A Level
DECLARE Minutes : INTEGERDECLARE Hours : INTEGERMinutes ← 135Hours ← Minutes DIV 60OUTPUT Hours

2.3

Remainder (modulo)

% becomes the operator a MOD b.

Java
int n = 17;if (n % 2 == 0) {    System.out.println("even");} else {    System.out.println("odd");}
A Level
DECLARE N : INTEGERN ← 17IF N MOD 2 = 0 THEN   OUTPUT "even"ELSE   OUTPUT "odd"ENDIF

2.4

Power

This standard has no power operator, so the expression is copied and flagged. Multiply instead (side * side).

Java
double side = 5;double area = Math.pow(side, 2);System.out.println(area);
A Level
DECLARE Side : REALDECLARE Area : REALSide ← 5Area ← Math.pow(side, 2)OUTPUT Area
  • Not directly available in A Level: The ** operator has no Cambridge A Level pseudocode equivalent. It was copied unchanged.

2.5

Comparisons

Equality is a single =; not-equal is <>.

Java
int x = 4;int y = 9;System.out.println(x == y);System.out.println(x != y);System.out.println(x <= y);System.out.println(x >= y);
A Level
DECLARE X : INTEGERDECLARE Y : INTEGERX ← 4Y ← 9OUTPUT X = YOUTPUT X <> YOUTPUT X <= YOUTPUT X >= Y

2.6

Logical and / or / not

Java &&, ||, ! and Python and, or, not all become the capitalised words AND, OR, NOT.

Java
int age = 15;boolean member = true;if (age >= 12 && age <= 18) {    System.out.println("teen");}if (age < 5 || age > 65) {    System.out.println("free entry");}if (!member) {    System.out.println("please register");}
A Level
DECLARE Age : INTEGERDECLARE Member : BOOLEANAge ← 15Member ← TRUEIF Age >= 12 AND Age <= 18 THEN   OUTPUT "teen"ENDIFIF Age < 5 OR Age > 65 THEN   OUTPUT "free entry"ENDIFIF NOT Member THEN   OUTPUT "please register"ENDIF

2.7

Joining strings

A Level joins strings with &.

Java
String first = "Ada";String last = "Lovelace";String full = first + " " + last;System.out.println(full);
A Level
DECLARE First : STRINGDECLARE Last : STRINGDECLARE Full : STRINGFirst ← "Ada"Last ← "Lovelace"Full ← First & " " & LastOUTPUT Full

Exercises1

Q1.Convert a number of seconds into minutes and remaining seconds.

int seconds = 200;int minutes = seconds / 60;int rest = seconds % 60;System.out.println(minutes);System.out.println(rest);
Show answer
Answer
DECLARE Seconds : INTEGERDECLARE Minutes : INTEGERDECLARE Rest : INTEGERSeconds ← 200Minutes ← Seconds DIV 60Rest ← Seconds MOD 60OUTPUT MinutesOUTPUT Rest

03Selection

A Level writes IF condition THEN on one line, then ELSE and ENDIF. There is no ELSEIF, so an elif chain becomes nested IFs.

Examples5

3.1

If

THEN goes at the end of the IF line.

Java
int temp = 31;if (temp > 30) {    System.out.println("hot");}
A Level
DECLARE Temp : INTEGERTemp ← 31IF Temp > 30 THEN   OUTPUT "hot"ENDIF

3.2

If … else

The else branch runs when the condition is false. Only one of the two branches runs.

Java
int mark = 64;if (mark >= 50) {    System.out.println("pass");} else {    System.out.println("fail");}
A Level
DECLARE Mark : INTEGERMark ← 64IF Mark >= 50 THEN   OUTPUT "pass"ELSE   OUTPUT "fail"ENDIF

3.3

Else-if chain

There is no else-if keyword, so each extra branch is nested inside the ELSE of the one before. Check the order of the tests: the first true branch wins.

Java
int mark = 72;String grade;if (mark >= 80) {    grade = "A";} else if (mark >= 70) {    grade = "B";} else if (mark >= 60) {    grade = "C";} else {    grade = "U";}System.out.println(grade);
A Level
DECLARE Mark : INTEGERDECLARE Grade : STRINGMark ← 72IF Mark >= 80 THEN   Grade ← "A"ELSE   IF Mark >= 70 THEN      Grade ← "B"   ELSE      IF Mark >= 60 THEN         Grade ← "C"      ELSE         Grade ← "U"      ENDIF   ENDIFENDIFOUTPUT Grade

3.4

Nested if

An if inside another if. Indentation shows which ELSE belongs to which IF.

Java
int age = 17;boolean hasTicket = true;if (hasTicket) {    if (age >= 18) {        System.out.println("enter");    } else {        System.out.println("adult needed");    }} else {    System.out.println("buy a ticket");}
A Level
DECLARE Age : INTEGERDECLARE HasTicket : BOOLEANAge ← 17HasTicket ← TRUEIF HasTicket THEN   IF Age >= 18 THEN      OUTPUT "enter"   ELSE      OUTPUT "adult needed"   ENDIFELSE   OUTPUT "buy a ticket"ENDIF

Exercises1

Q1.Print "freezing" below 0, "cold" below 15 and "warm" otherwise.

Scanner sc = new Scanner(System.in);System.out.print("Temperature: ");int temp = sc.nextInt();if (temp < 0) {    System.out.println("freezing");} else if (temp < 15) {    System.out.println("cold");} else {    System.out.println("warm");}
Show answer
Answer
DECLARE Temp : INTEGEROUTPUT "Temperature: "INPUT TempIF Temp < 0 THEN   OUTPUT "freezing"ELSE   IF Temp < 15 THEN      OUTPUT "cold"   ELSE      OUTPUT "warm"   ENDIFENDIF

04Loops

A Level has FOR I ← A TO B STEP S … NEXT I, WHILE … ENDWHILE (no DO) and REPEAT … UNTIL. A FOR loop includes its end value, so range(n) becomes 0 TO N - 1.

Examples8

4.1

Count from 0 to n − 1

range(n) stops before n, but a Cambridge FOR includes its end value, so the end becomes N - 1.

Java
int n = 5;for (int i = 0; i < n; i++) {    System.out.println(i);}
A Level
DECLARE N : INTEGERDECLARE I : INTEGERN ← 5FOR I ← 0 TO N - 1   OUTPUT INEXT I

4.2

Count with a step

STEP sets the increase. The end is the last value that can be reached (19 here, the loop shows 0, 5, 10, 15).

Java
for (int i = 0; i < 20; i += 5) {    System.out.println(i);}
A Level
DECLARE I : INTEGERFOR I ← 0 TO 19 STEP 5   OUTPUT INEXT I

4.3

Count down

A negative STEP counts down. range(10, 0, -1) stops before 0, so the end value is 1.

Java
for (int i = 10; i > 0; i--) {    System.out.println(i);}System.out.println("Lift off");
A Level
DECLARE I : INTEGERFOR I ← 10 TO 1 STEP -1   OUTPUT INEXT IOUTPUT "Lift off"

4.4

While with a condition

WHILE condition … ENDWHILE. The 9618 guide has no DO.

Java
double balance = 100;int years = 0;while (balance < 200) {    balance = balance * 1.1;    years = years + 1;}System.out.println(years);
A Level
DECLARE Balance : REALDECLARE Years : INTEGERBalance ← 100Years ← 0WHILE Balance < 200   Balance ← Balance * 1.1   Years ← Years + 1ENDWHILEOUTPUT Years

4.5

Input validation loop

Python's while loop becomes WHILE. Java's do … while becomes Cambridge's post-condition loop REPEAT … UNTIL, with the condition reversed by NOT.

Java
Scanner sc = new Scanner(System.in);int mark;do {    System.out.print("Mark (0-100): ");    mark = sc.nextInt();} while (mark < 0 || mark > 100);System.out.println(mark);
A Level
DECLARE Mark : INTEGERREPEAT   OUTPUT "Mark (0-100): "   INPUT MarkUNTIL NOT (Mark < 0 OR Mark > 100)OUTPUT Mark

4.6

Loop over every element of an array

Cambridge has no for-each loop, so the converter loops over the indexes of the array (its size is known from the declaration).

Java
String[] names = {"Ali", "Bea", "Cai"};for (String name : names) {    System.out.println(name);}
A Level
DECLARE Names : ARRAY[0:2] OF STRINGDECLARE I : INTEGERDECLARE Name : STRINGNames[0] ← "Ali"Names[1] ← "Bea"Names[2] ← "Cai"FOR I ← 0 TO 2   Name ← Names[I]   OUTPUT NameNEXT I

4.7

Nested loops

The inner loop runs completely for every pass of the outer loop (9 outputs here).

Java
for (int row = 1; row < 4; row++) {    for (int col = 1; col < 4; col++) {        System.out.println(row * col);    }}
A Level
DECLARE Row : INTEGERDECLARE Col : INTEGERFOR Row ← 1 TO 3   FOR Col ← 1 TO 3      OUTPUT Row * Col   NEXT ColNEXT Row

4.8

Break / continue

Pseudocode standards have no break or continue, so they are copied and flagged. Rewrite the loop with a condition (see the linear search in Chapter 9).

Java
int[] nums = {4, -1, 7, 0, 3};for (int n : nums) {    if (n < 0) {        continue;    }    if (n == 0) {        break;    }    System.out.println(n);}
A Level
DECLARE Nums : ARRAY[0:4] OF INTEGERDECLARE I : INTEGERDECLARE N : INTEGERNums[0] ← 4Nums[1] ← -1Nums[2] ← 7Nums[3] ← 0Nums[4] ← 3FOR I ← 0 TO 4   N ← Nums[I]   IF N < 0 THEN      continue;   ENDIF   IF N = 0 THEN      break;   ENDIF   OUTPUT NNEXT I
  • Not directly available in A Level: continue has no Cambridge pseudocode equivalent. It was copied unchanged.
  • Not directly available in A Level: break has no Cambridge pseudocode equivalent. It was copied unchanged.

Exercises2

Q1.Add up the numbers from 1 to 10 and print the total.

int total = 0;for (int i = 1; i <= 10; i++) {    total = total + i;}System.out.println(total);
Show answer
Answer
DECLARE Total : INTEGERDECLARE I : INTEGERTotal ← 0FOR I ← 1 TO 10   Total ← Total + INEXT IOUTPUT Total

Q2.Keep asking for a password until the user types "open".

Scanner sc = new Scanner(System.in);String word;do {    System.out.print("Password: ");    word = sc.nextLine();} while (!word.equals("open"));System.out.println("Unlocked");
Show answer
Answer
DECLARE Word : STRINGREPEAT   OUTPUT "Password: "   INPUT WordUNTIL Word = "open"OUTPUT "Unlocked"

05Arrays & lists

Cambridge arrays have a fixed size and type, declared with DECLARE Name : ARRAY[0:n] OF TYPE. The converter uses a lower bound of 0 so your indexes stay the same, and fills the values one element at a time.

Examples7

5.1

Create with values

The array is declared with bounds [0:3] (four elements), then each element is assigned.

Java
int[] scores = {12, 7, 19, 5};System.out.println(scores[0]);
A Level
DECLARE Scores : ARRAY[0:3] OF INTEGERScores[0] ← 12Scores[1] ← 7Scores[2] ← 19Scores[3] ← 5OUTPUT Scores[0]

5.2

Fixed-size array filled with 0

The array is declared with 5 elements and filled with 0 by a FOR loop.

Java
int[] counts = new int[5];System.out.println(counts[2]);
A Level
DECLARE Counts : ARRAY[0:4] OF INTEGERDECLARE I : INTEGERFOR I ← 0 TO 4   Counts[I] ← 0NEXT IOUTPUT Counts[2]

5.3

Read and update an element

Square brackets read and write one element; the index is unchanged.

Java
int[] stock = {3, 8, 2};stock[1] = stock[1] - 1;System.out.println(stock[1]);
A Level
DECLARE Stock : ARRAY[0:2] OF INTEGERStock[0] ← 3Stock[1] ← 8Stock[2] ← 2Stock[1] ← Stock[1] - 1OUTPUT Stock[1]

5.4

Length

A Cambridge array's size is fixed by its declaration, so the converter writes the number itself.

Java
int[] temps = {21, 25, 19, 23};System.out.println(temps.length);
A Level
DECLARE Temps : ARRAY[0:3] OF INTEGERTemps[0] ← 21Temps[1] ← 25Temps[2] ← 19Temps[3] ← 23OUTPUT 4

5.5

Last element

The last index is the upper bound from the declaration (3 here).

Java
int[] temps = {21, 25, 19, 23};int last = temps[temps.length - 1];System.out.println(last);
A Level
DECLARE Temps : ARRAY[0:3] OF INTEGERDECLARE Last : INTEGERTemps[0] ← 21Temps[1] ← 25Temps[2] ← 19Temps[3] ← 23Last ← Temps[3]OUTPUT Last

5.6

2-D array

A 2-D array is declared ARRAY[0:rows-1, 0:cols-1] and accessed with one pair of brackets: Grid[row, col].

Java
int[][] grid = {{1, 2, 3}, {4, 5, 6}};grid[1][2] = 0;System.out.println(grid[0][1]);
A Level
DECLARE Grid : ARRAY[0:1, 0:2] OF INTEGERGrid[0, 0] ← 1Grid[0, 1] ← 2Grid[0, 2] ← 3Grid[1, 0] ← 4Grid[1, 1] ← 5Grid[1, 2] ← 6Grid[1, 2] ← 0OUTPUT Grid[0, 1]

5.7

Add to a list

Cambridge arrays have a fixed size, so an empty list and append() cannot be converted. Declare an array big enough and keep a count of how many slots are used.

Java
ArrayList<Integer> evens = new ArrayList<>();for (int i = 1; i < 11; i++) {    if (i % 2 == 0) {        evens.add(i);    }}System.out.println(evens);
A Level
DECLARE Evens : <TYPE>DECLARE I : INTEGERArrayList<Integer> evens = new ArrayList<>();FOR I ← 1 TO 10   IF I MOD 2 = 0 THEN      evens.add(i);   ENDIFNEXT IOUTPUT Evens
  • The type of evens could not be inferred.
  • Not directly available in A Level: Cambridge arrays have a fixed size, so empty lists have no Cambridge pseudocode equivalent. It was copied unchanged.
  • Not directly available in A Level: Cambridge arrays have a fixed size, so append() has no Cambridge pseudocode equivalent. It was copied unchanged.

Exercises1

Q1.Double every value in an array, then print the first one.

int[] values = {3, 6, 9};for (int i = 0; i < values.length; i++) {    values[i] = values[i] * 2;}System.out.println(values[0]);
Show answer
Answer
DECLARE Values : ARRAY[0:2] OF INTEGERDECLARE I : INTEGERValues[0] ← 3Values[1] ← 6Values[2] ← 9FOR I ← 0 TO 2   Values[I] ← Values[I] * 2NEXT IOUTPUT Values[0]

06Strings

A Level has string functions: LENGTH(s), MID(s, start, length) and & to join. MID counts characters from 1, and UCASE / LCASE only change single characters.

Examples5

6.1

Length

len(word) / word.length() becomes LENGTH(word).

Java
String word = "algorithm";System.out.println(word.length());
A Level
DECLARE Word : STRINGWord ← "algorithm"OUTPUT LENGTH(Word)

6.2

One character

MID(Word, 1, 1) takes 1 character from position 1. Positions start at 1, so index 0 becomes 1.

Java
String word = "algorithm";char first = word.charAt(0);System.out.println(first);
A Level
DECLARE Word : STRINGDECLARE First : STRINGWord ← "algorithm"First ← MID(Word, 1, 1)OUTPUT First

6.3

Upper / lower case

In 9618, UCASE and LCASE only take a single character, so changing a whole string is flagged. Loop over the characters with MID instead.

Java
String city = "Paris";System.out.println(city.toUpperCase());System.out.println(city.toLowerCase());
A Level
DECLARE City : STRINGCity ← "Paris"OUTPUT city.toUpperCase()OUTPUT city.toLowerCase()
  • Not directly available in A Level: UCASE only takes a single character in Cambridge A Level pseudocode. It was copied unchanged.
  • Not directly available in A Level: LCASE only takes a single character in Cambridge A Level pseudocode. It was copied unchanged.

6.4

Compare two strings

Java must use .equals() to compare strings; in pseudocode it is an ordinary =.

Java
Scanner sc = new Scanner(System.in);System.out.print("Password: ");String password = sc.nextLine();if (password.equals("secret")) {    System.out.println("Welcome");} else {    System.out.println("Wrong password");}
A Level
DECLARE Password : STRINGOUTPUT "Password: "INPUT PasswordIF Password = "secret" THEN   OUTPUT "Welcome"ELSE   OUTPUT "Wrong password"ENDIF

6.5

Joining strings with numbers

A Level joins strings with &, but a number must be turned into a string first (9618 has NUM_TO_STR), so this line is flagged.

Java
String name = "Sam";int score = 8;String message = name + " scored " + score;System.out.println(message);
A Level
DECLARE Name : STRINGDECLARE Score : INTEGERDECLARE Message : STRINGName ← "Sam"Score ← 8Message ← name + " scored " + scoreOUTPUT Message
  • Not directly available in A Level: String concatenation could not be converted to Cambridge pseudocode. It was copied unchanged.

Exercises1

Q1.Ask for a word and print how many characters it has.

Scanner sc = new Scanner(System.in);System.out.print("Word: ");String word = sc.nextLine();System.out.println(word.length());
Show answer
Answer
DECLARE Word : STRINGOUTPUT "Word: "INPUT WordOUTPUT LENGTH(Word)

07Subprograms

A Level separates PROCEDURE … ENDPROCEDURE (called with CALL) from FUNCTION … RETURNS TYPE … ENDFUNCTION. Every parameter has a type, and an array the procedure changes is passed BYREF.

Examples5

7.1

Procedure with a parameter

A procedure is called with CALL Name(args). The parameter is given a type.

Java
public class Main {    static void greet(String name) {        System.out.println("Hello " + name);    }​    public static void main(String[] args) {        greet("Kim");    }}
A Level
PROCEDURE Greet(Name : STRING)   OUTPUT "Hello ", NameENDPROCEDURECALL Greet("Kim")

7.2

Function returning a value

FUNCTION Name(params) RETURNS TYPE. The return type is required.

Java
public class Main {    static int area(int width, int height) {        return width * height;    }​    public static void main(String[] args) {        System.out.println(area(4, 6));    }}
A Level
FUNCTION Area(Width : INTEGER, Height : INTEGER) RETURNS INTEGER   RETURN Width * HeightENDFUNCTIONOUTPUT Area(4, 6)

7.3

Function with no parameters

A Level keeps the empty brackets: GetMark(). Local variables are declared inside the function.

Java
public class Main {    static int getMark() {        Scanner sc = new Scanner(System.in);        System.out.print("Mark: ");        int mark = sc.nextInt();        return mark;    }​    public static void main(String[] args) {        int result = getMark();        System.out.println(result);    }}
A Level
DECLARE Result : INTEGERFUNCTION GetMark() RETURNS INTEGER   DECLARE Mark : INTEGER   OUTPUT "Mark: "   INPUT Mark   RETURN MarkENDFUNCTIONResult ← GetMark()OUTPUT Result

7.4

Procedure that changes an array

Because the procedure changes the array, it is passed BYREF so the change is visible to the caller.

Java
public class Main {    static void reset(int[] nums) {        for (int i = 0; i < nums.length; i++) {            nums[i] = 0;        }    }​    public static void main(String[] args) {        int[] data = {4, 5, 6};        reset(data);        System.out.println(data[0]);    }}
A Level
DECLARE Data : ARRAY[0:2] OF INTEGERPROCEDURE Reset(BYREF Nums : ARRAY[0:2] OF INTEGER)   DECLARE I : INTEGER   FOR I ← 0 TO 2      Nums[I] ← 0   NEXT IENDPROCEDUREData[0] ← 4Data[1] ← 5Data[2] ← 6CALL Reset(Data)OUTPUT Data[0]

7.5

Recursion (factorial)

A recursive function calls itself. It needs a base case (n <= 1) that stops the calls.

Java
public class Main {    static int factorial(int n) {        if (n <= 1) {            return 1;        }        return n * factorial(n - 1);    }​    public static void main(String[] args) {        System.out.println(factorial(5));    }}
A Level
FUNCTION Factorial(N : INTEGER) RETURNS INTEGER   IF N <= 1 THEN      RETURN 1   ENDIF   RETURN N * Factorial(N - 1)ENDFUNCTIONOUTPUT Factorial(5)

Exercises1

Q1.Write a function that returns the larger of two numbers.

public class Main {    static int larger(int a, int b) {        if (a > b) {            return a;        }        return b;    }​    public static void main(String[] args) {        System.out.println(larger(3, 8));    }}
Show answer
Answer
FUNCTION Larger(A : INTEGER, B : INTEGER) RETURNS INTEGER   IF A > B THEN      RETURN A   ENDIF   RETURN BENDFUNCTIONOUTPUT Larger(3, 8)

08Random numbers

A Level has RAND(x), which gives a real number from 0 up to x. A whole number is made with INT and adding 1.

Examples1

8.1

Dice roll (1–6)

RAND(6) gives 0 up to (not including) 6; INT drops the decimals and + 1 gives 1 to 6.

Java
Random rand = new Random();int roll = rand.nextInt(6) + 1;System.out.println(roll);
A Level
DECLARE Roll : INTEGERRoll ← INT(RAND(6)) + 1OUTPUT Roll

Exercises1

Q1.Pick a random number from 1 to 100 and print whether it is above 50.

Random rand = new Random();int n = rand.nextInt(100) + 1;if (n > 50) {    System.out.println("high");} else {    System.out.println("low");}
Show answer
Answer
DECLARE N : INTEGERN ← INT(RAND(100)) + 1IF N > 50 THEN   OUTPUT "high"ELSE   OUTPUT "low"ENDIF

09Complete programs

These are the standard algorithms examiners ask for. Each one combines variables, loops, selection and arrays from the earlier chapters. Read the pseudocode line by line and match it to the source.

Examples5

9.2

Total and average

Start the total at 0, add each element, then divide by the number of elements. The average is a real number.

Java
int[] marks = {56, 78, 91, 64, 70};int total = 0;for (int m : marks) {    total = total + m;}double average = (double) total / marks.length;System.out.println(total);System.out.println(average);
A Level
DECLARE Marks : ARRAY[0:4] OF INTEGERDECLARE Total : INTEGERDECLARE I : INTEGERDECLARE M : INTEGERDECLARE Average : REALMarks[0] ← 56Marks[1] ← 78Marks[2] ← 91Marks[3] ← 64Marks[4] ← 70Total ← 0FOR I ← 0 TO 4   M ← Marks[I]   Total ← Total + MNEXT IAverage ← Total / 5OUTPUT TotalOUTPUT Average

9.3

Maximum value

Assume the first element is the largest, then compare it with every other element.

Java
int[] temps = {18, 24, 21, 27, 19};int highest = temps[0];for (int i = 1; i < temps.length; i++) {    if (temps[i] > highest) {        highest = temps[i];    }}System.out.println(highest);
A Level
DECLARE Temps : ARRAY[0:4] OF INTEGERDECLARE Highest : INTEGERDECLARE I : INTEGERTemps[0] ← 18Temps[1] ← 24Temps[2] ← 21Temps[3] ← 27Temps[4] ← 19Highest ← Temps[0]FOR I ← 1 TO 4   IF Temps[I] > Highest THEN      Highest ← Temps[I]   ENDIFNEXT IOUTPUT Highest

9.4

Counting matches

A counter starts at 0 and goes up by 1 each time an element meets the condition.

Java
int[] marks = {45, 82, 67, 39, 90};int passes = 0;for (int m : marks) {    if (m >= 50) {        passes = passes + 1;    }}System.out.println(passes);
A Level
DECLARE Marks : ARRAY[0:4] OF INTEGERDECLARE Passes : INTEGERDECLARE I : INTEGERDECLARE M : INTEGERMarks[0] ← 45Marks[1] ← 82Marks[2] ← 67Marks[3] ← 39Marks[4] ← 90Passes ← 0FOR I ← 0 TO 4   M ← Marks[I]   IF M >= 50 THEN      Passes ← Passes + 1   ENDIFNEXT IOUTPUT Passes

9.5

Bubble sort

Compare neighbours and swap them if they are in the wrong order. After each pass the largest remaining value is at the end, so the inner loop gets shorter.

Java
int[] data = {5, 2, 9, 1, 7};int n = data.length;for (int i = 0; i < n - 1; i++) {    for (int j = 0; j < n - 1 - i; j++) {        if (data[j] > data[j + 1]) {            int temp = data[j];            data[j] = data[j + 1];            data[j + 1] = temp;        }    }}for (int x : data) {    System.out.println(x);}
A Level
DECLARE Data : ARRAY[0:4] OF INTEGERDECLARE N : INTEGERDECLARE I : INTEGERDECLARE J : INTEGERDECLARE Temp : INTEGERDECLARE K : INTEGERDECLARE X : INTEGERData[0] ← 5Data[1] ← 2Data[2] ← 9Data[3] ← 1Data[4] ← 7N ← 5FOR I ← 0 TO N - 2   FOR J ← 0 TO N - 1 - I - 1      IF Data[J] > Data[J + 1] THEN         Temp ← Data[J]         Data[J] ← Data[J + 1]         Data[J + 1] ← Temp      ENDIF   NEXT JNEXT IFOR K ← 0 TO 4   X ← Data[K]   OUTPUT XNEXT K

Exercises2

Q1.Find the smallest value in an array.

int[] nums = {8, 3, 11, 5};int lowest = nums[0];for (int i = 1; i < nums.length; i++) {    if (nums[i] < lowest) {        lowest = nums[i];    }}System.out.println(lowest);
Show answer
Answer
DECLARE Nums : ARRAY[0:3] OF INTEGERDECLARE Lowest : INTEGERDECLARE I : INTEGERNums[0] ← 8Nums[1] ← 3Nums[2] ← 11Nums[3] ← 5Lowest ← Nums[0]FOR I ← 1 TO 3   IF Nums[I] < Lowest THEN      Lowest ← Nums[I]   ENDIFNEXT IOUTPUT Lowest

Q2.Count how many times the letter "a" appears in a word.

String word = "banana";int count = 0;for (int i = 0; i < word.length(); i++) {    if (word.charAt(i) == 'a') {        count = count + 1;    }}System.out.println(count);
Show answer
Answer
DECLARE Word : STRINGDECLARE Count : INTEGERDECLARE I : INTEGERWord ← "banana"Count ← 0FOR I ← 0 TO LENGTH(Word) - 1   IF MID(Word, I + 1, 1) = "a" THEN      Count ← Count + 1   ENDIFNEXT IOUTPUT Count