Java → IB Pseudocode
IB Computer Science
Key rules
- 01Variable names are written in CAPITALS (SCORE, TOTAL); subprogram names keep their case.
- 02Assignment uses
=, and printing usesoutput; reading a value usesinput NAME. - 03Counting loops are
loop I from A to B, where both ends are included, so range(n) becomes 0 to N - 1. - 04Selection is
if … then … else if … else … end if. - 05Arrays are 0-based like Python and Java, and their size is
ARRAY.length.
Contents10 sections
Quick reference
| Concept | Java | IB |
|---|---|---|
| Assignment | int x = 5; | X = 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 Xend if |
| 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 2end if |
| While loop | while (x < 3) { x = x + 1;} | loop while X < 3 X = X + 1end loop |
| Counting loop | for (int i = 0; i < 5; i++) { System.out.println(i);} | loop I from 0 to 4 output Iend loop |
| Repeat n times | for (int i = 0; i < 3; i++) { System.out.println("Hi");} | loop I from 0 to 2 output "Hi"end loop |
| For each | for (int x : xs) { System.out.println(x);} | loop I from 0 to XS.length - 1 X = XS[I] output Xend loop |
| Create array | int[] xs = {4, 7, 9}; | XS = [4, 7, 9] |
| Array access | System.out.println(xs[0]); | output XS[0] |
| Length | System.out.println(xs.length); | output XS.length |
| Function + return | static int twice(int n) { return n * 2;}// in main:System.out.println(twice(4)); | function twice(N) returns value return N * 2end functionoutput twice(4) |
| Procedure + call | static void show(int n) { System.out.println(n);}// in main:show(3); | procedure show(N) output Nend procedureshow(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 = RANDOM.randint(0, 5) + 1 |
01Basics
IB pseudocode looks a lot like Python. The biggest visible change is that variable names are written in CAPITALS, and printing becomes output. Values do not need a declared type.
Examples8
1.1
Comment
Comments start with // in every standard. Write them before the line they explain.
// Calculate the area of a rectangleint area = 4 * 3;// Calculate the area of a rectangleAREA = 4 * 31.2
Assign a variable
IB uses = for assignment and CAPITAL names. Updating a variable is written in full (SCORE = SCORE + 10).
int score = 0;score = score + 10;SCORE = 0SCORE = SCORE + 101.3
Variables of different types
Types are not written in IB pseudocode. Booleans are lower-case true / false.
int count = 5;double price = 2.75;String name = "Ana";boolean found = false;COUNT = 5PRICE = 2.75NAME = "Ana"FOUND = false1.4
Constant
There is no constant keyword, so a constant is just a variable written in capitals that you never change.
final int MAX_SIZE = 50;System.out.println(MAX_SIZE);MAX_SIZE = 50output MAX_SIZEint total = 42;System.out.println(total);TOTAL = 42output TOTAL1.6
Output text and a value
Several values can be listed after output, separated by commas.
int age = 16;System.out.println("Age: " + age);AGE = 16output "Age: " + AGEScanner sc = new Scanner(System.in);System.out.print("Enter your name: ");String name = sc.nextLine();System.out.println("Hello " + name);output "Enter your name: "input NAMEoutput "Hello " + NAME1.8
Input a number
Converting the input with int() (or sc.nextInt()) is not written in pseudocode; input simply reads a value.
Scanner sc = new Scanner(System.in);System.out.print("Enter your age: ");int age = sc.nextInt();System.out.println(age + 1);output "Enter your age: "input AGEoutput AGE + 1Exercises1
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 answerHide answer
output "Name: "input NAMEoutput "Favourite number: "input NUMBERoutput NAME + " " + NUMBER02Operators
IB uses div and mod for integer division and remainder, ≠ for not-equal and the capitalised words AND, OR, NOT. There is no power operator.
Examples7
2.1
Arithmetic
+ - * / are the same in every standard. / always gives a real (decimal) result.
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 = 7B = 2output A + Boutput A - Boutput A * Boutput A / Bint minutes = 135;int hours = minutes / 60;System.out.println(hours);MINUTES = 135HOURS = MINUTES div 60output HOURS2.3
Remainder (modulo)
% becomes mod. Testing mod 2 = 0 is the usual way to check for an even number.
int n = 17;if (n % 2 == 0) { System.out.println("even");} else { System.out.println("odd");}N = 17if N mod 2 = 0 then output "even"else output "odd"end if2.4
Power
This standard has no power operator, so the expression is copied and flagged. Multiply instead (side * side).
double side = 5;double area = Math.pow(side, 2);System.out.println(area);SIDE = 5AREA = Math.pow(side, 2)output AREA- Not directly available in IB: The ** operator has no IB pseudocode equivalent. It was copied unchanged.
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);X = 4Y = 9output X = Youtput X ≠ Youtput X <= Youtput X >= Y2.6
Logical and / or / not
Java &&, ||, ! and Python and, or, not all become the capitalised words AND, OR, NOT.
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");}AGE = 15MEMBER = trueif AGE >= 12 AND AGE <= 18 then output "teen"end ifif AGE < 5 OR AGE > 65 then output "free entry"end ifif NOT MEMBER then output "please register"end ifString first = "Ada";String last = "Lovelace";String full = first + " " + last;System.out.println(full);FIRST = "Ada"LAST = "Lovelace"FULL = FIRST + " " + LASToutput FULLExercises1
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 answerHide answer
SECONDS = 200MINUTES = SECONDS div 60REST = SECONDS mod 60output MINUTESoutput REST03Selection
IB selection reads like English: if CONDITION then … else if … else … end if. Every if is closed with end if.
Examples5
int temp = 31;if (temp > 30) { System.out.println("hot");}TEMP = 31if TEMP > 30 then output "hot"end if3.2
If … else
The else branch runs when the condition is false. Only one of the two branches runs.
int mark = 64;if (mark >= 50) { System.out.println("pass");} else { System.out.println("fail");}MARK = 64if MARK >= 50 then output "pass"else output "fail"end if3.3
Else-if chain
IB has else if, so the chain stays flat with one end if at the end.
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);MARK = 72if MARK >= 80 then GRADE = "A"else if MARK >= 70 then GRADE = "B"else if MARK >= 60 then GRADE = "C"else GRADE = "U"end ifoutput GRADE3.4
Nested if
An if inside another if. Indentation shows which ELSE belongs to which IF.
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");}AGE = 17HASTICKET = trueif HASTICKET then if AGE >= 18 then output "enter" else output "adult needed" end ifelse output "buy a ticket"end ifExercises1
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 answerHide answer
output "Temperature: "input TEMPif TEMP < 0 then output "freezing"else if TEMP < 15 then output "cold"else output "warm"end if04Loops
IB has two loops: loop I from A to B (both ends included) and loop while CONDITION. Python range(n) stops before n, so the converter writes from 0 to N - 1. Loops with a step are written as a while loop.
Examples8
4.1
Count from 0 to n − 1
range(n) stops before n, but loop … to includes its end, so the end becomes N - 1.
int n = 5;for (int i = 0; i < n; i++) { System.out.println(i);}N = 5loop I from 0 to N - 1 output Iend loop4.2
Count with a step
IB's counting loop has no step, so a stepped loop is written as loop while with the counter updated at the end.
for (int i = 0; i < 20; i += 5) { System.out.println(i);}I = 0loop while I < 20 output I I = I + 5end loopfor (int i = 10; i > 0; i--) { System.out.println(i);}System.out.println("Lift off");I = 10loop while I > 0 output I I = I - 1end loopoutput "Lift off"4.4
While with a condition
loop while CONDITION … end loop. The condition is checked before each pass.
double balance = 100;int years = 0;while (balance < 200) { balance = balance * 1.1; years = years + 1;}System.out.println(years);BALANCE = 100YEARS = 0loop while BALANCE < 200 BALANCE = BALANCE * 1.1 YEARS = YEARS + 1end loopoutput YEARS4.5
Input validation loop
Python uses a while loop and Java a do … while. IB has no post-condition loop, so both become: read once, then loop while the value is invalid.
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);output "Mark (0-100): "input MARKloop while MARK < 0 OR MARK > 100 output "Mark (0-100): " input MARKend loopoutput MARK4.6
Loop over every element of an array
IB has no for-each loop, so the converter loops over the indexes 0 to length - 1 and reads each element.
String[] names = {"Ali", "Bea", "Cai"};for (String name : names) { System.out.println(name);}NAMES = ["Ali", "Bea", "Cai"]loop I from 0 to NAMES.length - 1 NAME = NAMES[I] output NAMEend loop4.7
Nested loops
The inner loop runs completely for every pass of the outer loop (9 outputs here).
for (int row = 1; row < 4; row++) { for (int col = 1; col < 4; col++) { System.out.println(row * col); }}loop ROW from 1 to 3 loop COL from 1 to 3 output ROW * COL end loopend loop4.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).
int[] nums = {4, -1, 7, 0, 3};for (int n : nums) { if (n < 0) { continue; } if (n == 0) { break; } System.out.println(n);}NUMS = [4, -1, 7, 0, 3]loop I from 0 to NUMS.length - 1 N = NUMS[I] if N < 0 then continue; end if if N = 0 then break; end if output Nend loop- Not directly available in IB: continue has no IB pseudocode equivalent. It was copied unchanged.
- Not directly available in IB: break has no IB 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 answerHide answer
TOTAL = 0loop I from 1 to 10 TOTAL = TOTAL + Iend loopoutput TOTALQ2.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 answerHide answer
output "Password: "input WORDloop while NOT WORD = "open" output "Password: " input WORDend loopoutput "Unlocked"05Arrays & lists
IB arrays look like Python lists: NAMES = ["Ali", "Bea"], indexes start at 0, and the size is NAMES.length. Lists that grow use addItem.
Examples7
int[] scores = {12, 7, 19, 5};System.out.println(scores[0]);SCORES = [12, 7, 19, 5]output SCORES[0]5.2
Fixed-size array filled with 0
[0] * 5 / new int[5] has no direct equivalent here, so it is copied and flagged. Write the list out, or fill it with a loop.
int[] counts = new int[5];System.out.println(counts[2]);COUNTS = new int[5]output COUNTS[2]- Not directly available in IB: List/string repetition has no IB pseudocode equivalent. It was copied unchanged.
5.3
Read and update an element
Square brackets read and write one element; the index is unchanged.
int[] stock = {3, 8, 2};stock[1] = stock[1] - 1;System.out.println(stock[1]);STOCK = [3, 8, 2]STOCK[1] = STOCK[1] - 1output STOCK[1]int[] temps = {21, 25, 19, 23};System.out.println(temps.length);TEMPS = [21, 25, 19, 23]output TEMPS.lengthint[] temps = {21, 25, 19, 23};int last = temps[temps.length - 1];System.out.println(last);TEMPS = [21, 25, 19, 23]LAST = TEMPS[TEMPS.length - 1]output LAST5.6
2-D array
Rows and columns are written with two pairs of brackets: GRID[row][col].
int[][] grid = {{1, 2, 3}, {4, 5, 6}};grid[1][2] = 0;System.out.println(grid[0][1]);GRID = [[1, 2, 3], [4, 5, 6]]GRID[1][2] = 0output GRID[0][1]ArrayList<Integer> evens = new ArrayList<>();for (int i = 1; i < 11; i++) { if (i % 2 == 0) { evens.add(i); }}System.out.println(evens);EVENS = []loop I from 1 to 10 if I mod 2 = 0 then EVENS.addItem(I) end ifend loopoutput EVENSExercises1
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 answerHide answer
VALUES = [3, 6, 9]loop I from 0 to VALUES.length - 1 VALUES[I] = VALUES[I] * 2end loopoutput VALUES[0]06Strings
IB keeps strings close to Python: .length for the length, WORD[0] for one character, and + to join.
Examples5
String word = "algorithm";System.out.println(word.length());WORD = "algorithm"output WORD.lengthString word = "algorithm";char first = word.charAt(0);System.out.println(first);WORD = "algorithm"FIRST = WORD[0]output FIRST6.3
Upper / lower case
IB has no standard case functions, so the method call is kept as it is.
String city = "Paris";System.out.println(city.toUpperCase());System.out.println(city.toLowerCase());CITY = "Paris"output CITY.upper()output CITY.lower()6.4
Compare two strings
Java must use .equals() to compare strings; in pseudocode it is an ordinary =.
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");}output "Password: "input PASSWORDif PASSWORD = "secret" then output "Welcome"else output "Wrong password"end if6.5
Joining strings with numbers
IB joins with +. Python's str() is kept so the number is turned into text.
String name = "Sam";int score = 8;String message = name + " scored " + score;System.out.println(message);NAME = "Sam"SCORE = 8MESSAGE = NAME + " scored " + SCOREoutput MESSAGEExercises1
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 answerHide answer
output "Word: "input WORDoutput WORD.length07Subprograms
IB has procedure NAME(PARAMS) … end procedure and function NAME(PARAMS) returns value … end function. A subprogram that returns something is a function.
Examples5
7.1
Procedure with a parameter
A def / void method with no return becomes procedure … end procedure; the call is just its name.
public class Main { static void greet(String name) { System.out.println("Hello " + name); } public static void main(String[] args) { greet("Kim"); }}procedure greet(NAME) output "Hello " + NAMEend proceduregreet("Kim")7.2
Function returning a value
Returning a value makes it a function … returns value.
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)); }}function area(WIDTH, HEIGHT) returns value return WIDTH * HEIGHTend functionoutput area(4, 6)7.3
Function with no parameters
A function with no parameters keeps its empty brackets.
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); }}function getMark() returns value output "Mark: " input MARK return MARKend functionRESULT = getMark()output RESULT7.4
Procedure that changes an array
The array is passed in and its elements are changed in place.
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]); }}procedure reset(NUMS) loop I from 0 to NUMS.length - 1 NUMS[I] = 0 end loopend procedureDATA = [4, 5, 6]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.
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)); }}function factorial(N) returns value if N <= 1 then return 1 end if return N * factorial(N - 1)end functionoutput 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 answerHide answer
function larger(A, B) returns value if A > B then return A end if return Bend functionoutput larger(3, 8)08Random numbers
IB has no official random function; the converter keeps a RANDOM.randint(a, b) style call so the meaning is clear.
Examples1
8.1
Dice roll (1–6)
The import random line has no IB equivalent and is flagged; the randint call is kept.
Random rand = new Random();int roll = rand.nextInt(6) + 1;System.out.println(roll);ROLL = RANDOM.randint(0, 5) + 1output ROLLExercises1
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 answerHide answer
N = RANDOM.randint(0, 99) + 1if N > 50 then output "high"else output "low"end if09Complete 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.1
Linear search
Checks each element in turn and stops when the target is found. A found flag in the loop condition is used instead of break.
String[] names = {"Ali", "Bea", "Cai", "Dev"};Scanner sc = new Scanner(System.in);System.out.print("Name: ");String target = sc.nextLine();boolean found = false;int i = 0;while (i < names.length && !found) { if (names[i].equals(target)) { found = true; } else { i = i + 1; }}if (found) { System.out.println("Found at " + i);} else { System.out.println("Not found");}NAMES = ["Ali", "Bea", "Cai", "Dev"]output "Name: "input TARGETFOUND = falseI = 0loop while I < NAMES.length AND NOT FOUND if NAMES[I] = TARGET then FOUND = true else I = I + 1 end ifend loopif FOUND then output "Found at " + Ielse output "Not found"end if9.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.
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);MARKS = [56, 78, 91, 64, 70]TOTAL = 0loop I from 0 to MARKS.length - 1 M = MARKS[I] TOTAL = TOTAL + Mend loopAVERAGE = TOTAL / MARKS.lengthoutput TOTALoutput AVERAGE9.3
Maximum value
Assume the first element is the largest, then compare it with every other element.
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);TEMPS = [18, 24, 21, 27, 19]HIGHEST = TEMPS[0]loop I from 1 to TEMPS.length - 1 if TEMPS[I] > HIGHEST then HIGHEST = TEMPS[I] end ifend loopoutput HIGHEST9.4
Counting matches
A counter starts at 0 and goes up by 1 each time an element meets the condition.
int[] marks = {45, 82, 67, 39, 90};int passes = 0;for (int m : marks) { if (m >= 50) { passes = passes + 1; }}System.out.println(passes);MARKS = [45, 82, 67, 39, 90]PASSES = 0loop I from 0 to MARKS.length - 1 M = MARKS[I] if M >= 50 then PASSES = PASSES + 1 end ifend loopoutput PASSES9.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.
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);}DATA = [5, 2, 9, 1, 7]N = DATA.lengthloop I from 0 to N - 2 loop J from 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 end if end loopend looploop K from 0 to DATA.length - 1 X = DATA[K] output Xend loopExercises2
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 answerHide answer
NUMS = [8, 3, 11, 5]LOWEST = NUMS[0]loop I from 1 to NUMS.length - 1 if NUMS[I] < LOWEST then LOWEST = NUMS[I] end ifend loopoutput LOWESTQ2.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 answerHide answer
WORD = "banana"COUNT = 0loop I from 0 to WORD.length - 1 if WORD[I] = "a" then COUNT = COUNT + 1 end ifend loopoutput COUNT