Skip to content
Pseudocode Converter

Java → AP CSP Pseudocode

AP Computer Science Principles

Key rules

  1. 01Assignment uses ←; output is DISPLAY(x) and input is x ← INPUT().
  2. 02Loops are REPEAT n TIMES, REPEAT UNTIL(condition) and FOR EACH item IN list; there is no counting FOR loop.
  3. 03Lists are 1-based: the converter adds 1 to every index, so Python's names[0] becomes names[1].
  4. 04Subprograms are written PROCEDURE name(params) { … }, and values are returned with RETURN(x).
  5. 05Blocks use braces { }; there is no ELSE IF, so an elif chain becomes nested IF … ELSE.
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

ConceptJavaAP CSP
Assignment
int x = 5;
x ← 5
Output
System.out.println("Hi");
DISPLAY("Hi")
Input
String name = sc.nextLine();
name ← INPUT()
If
if (x > 3) {    System.out.println(x);}
IF(x > 3){   DISPLAY(x)}
Else if
if (x > 3) {    System.out.println(1);} else if (x > 1) {    System.out.println(2);}
IF(x > 3){   DISPLAY(1)}ELSE{   IF(x > 1)   {      DISPLAY(2)   }}
While loop
while (x < 3) {    x = x + 1;}
REPEAT UNTIL(x ≥ 3){   x ← x + 1}
Counting loop
for (int i = 0; i < 5; i++) {    System.out.println(i);}
i ← 0REPEAT UNTIL(i ≥ 5){   DISPLAY(i)   i ← i + 1}
Repeat n times
for (int i = 0; i < 3; i++) {    System.out.println("Hi");}
REPEAT 3 TIMES{   DISPLAY("Hi")}
For each
for (int x : xs) {    System.out.println(x);}
FOR EACH x IN xs{   DISPLAY(x)}
Create array
int[] xs = {4, 7, 9};
xs ← [4, 7, 9]
Array access
System.out.println(xs[0]);
DISPLAY(xs[1])
Length
System.out.println(xs.length);
DISPLAY(LENGTH(xs))
Function + return
static int twice(int n) {    return n * 2;}// in main:System.out.println(twice(4));
PROCEDURE twice(n){   RETURN(n * 2)}DISPLAY(twice(4))
Procedure + call
static void show(int n) {    System.out.println(n);}// in main:show(3);
PROCEDURE show(n){   DISPLAY(n)}show(3)
Integer division
int b = a / 2;
b ← a / 2

No equivalent

Remainder
int b = a % 2;
b ← a MOD 2
Not equal
System.out.println(a != 2);
DISPLAY(a ≠ 2)
And / or / not
System.out.println(a && !b || b);
DISPLAY(a AND NOT b OR b)
String join
String t = s + "cd";
t ← s + "cd"

No equivalent

Random 1–6
int r = rand.nextInt(6) + 1;
r ← RANDOM(0, 5) + 1

01Basics

AP CSP pseudocode uses an arrow ← for assignment so that it cannot be confused with the equality test =. Output is DISPLAY(…) and input is the expression INPUT(). Types are never written.

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;
AP CSP
// Calculate the area of a rectanglearea ← 4 * 3

1.2

Assign a variable

AP uses ← for assignment. Names keep the case you wrote them in.

Java
int score = 0;score = score + 10;
AP CSP
score ← 0score ← score + 10

1.3

Variables of different types

Types are not written in AP pseudocode. Booleans are true / false.

Java
int count = 5;double price = 2.75;String name = "Ana";boolean found = false;
AP CSP
count ← 5price ← 2.75name ← "Ana"found ← false

1.4

Constant

There is no constant keyword, so a constant is just a variable written in capitals that you never change.

Java
final int MAX_SIZE = 50;System.out.println(MAX_SIZE);
AP CSP
MAX_SIZE ← 50DISPLAY(MAX_SIZE)

1.5

Output a value

Printing becomes DISPLAY(…).

Java
int total = 42;System.out.println(total);
AP CSP
total ← 42DISPLAY(total)

1.6

Output text and a value

DISPLAY shows one value at a time, so print with several values becomes several DISPLAY lines. Joining with + is not part of AP pseudocode.

Java
int age = 16;System.out.println("Age: " + age);
AP CSP
age ← 16DISPLAY("Age: " + age)
  • Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.

1.7

Input text

INPUT() is an expression, so it appears on the right of ←. The prompt becomes a separate DISPLAY.

Java
Scanner sc = new Scanner(System.in);System.out.print("Enter your name: ");String name = sc.nextLine();System.out.println("Hello " + name);
AP CSP
DISPLAY("Enter your name: ")name ← INPUT()DISPLAY("Hello " + name)
  • Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.

1.8

Input a number

Converting the input with int() (or sc.nextInt()) is not written in pseudocode; input simply reads a value.

Java
Scanner sc = new Scanner(System.in);System.out.print("Enter your age: ");int age = sc.nextInt();System.out.println(age + 1);
AP CSP
DISPLAY("Enter your age: ")age ← INPUT()DISPLAY(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
DISPLAY("Name: ")name ← INPUT()DISPLAY("Favourite number: ")number ← INPUT()DISPLAY(name + " " + number)
  • Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.

02Operators

AP uses MOD for remainder and the symbols ≠, ≤, ≥. It has no integer-division operator and no way to join strings with +, so those are left as they are and flagged.

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);
AP CSP
a ← 7b ← 2DISPLAY(a + b)DISPLAY(a - b)DISPLAY(a * b)DISPLAY(a / b)

2.2

Integer division

AP pseudocode has no integer division, so the expression is copied and flagged. Rewrite it in your answer if you need it.

Java
int minutes = 135;int hours = minutes / 60;System.out.println(hours);
AP CSP
minutes ← 135hours ← minutes / 60DISPLAY(hours)
  • Not directly available in AP CSP: Integer division (//) has no AP pseudocode equivalent. It was copied unchanged.

2.3

Remainder (modulo)

% becomes MOD.

Java
int n = 17;if (n % 2 == 0) {    System.out.println("even");} else {    System.out.println("odd");}
AP CSP
n ← 17IF(n MOD 2 = 0){   DISPLAY("even")}ELSE{   DISPLAY("odd")}

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);
AP CSP
side ← 5area ← Math.pow(side, 2)DISPLAY(area)
  • Not directly available in AP CSP: The ** operator has no AP pseudocode equivalent. It was copied unchanged.

2.5

Comparisons

Equality is a single =; the others become ≠, ≤, ≥.

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);
AP CSP
x ← 4y ← 9DISPLAY(x = y)DISPLAY(x ≠ y)DISPLAY(x ≤ y)DISPLAY(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");}
AP CSP
age ← 15member ← trueIF(age ≥ 12 AND age ≤ 18){   DISPLAY("teen")}IF(age < 5 OR age > 65){   DISPLAY("free entry")}IF(NOT member){   DISPLAY("please register")}

2.7

Joining strings

AP pseudocode has no string-joining operator, so the + is copied and flagged.

Java
String first = "Ada";String last = "Lovelace";String full = first + " " + last;System.out.println(full);
AP CSP
first ← "Ada"last ← "Lovelace"full ← first + " " + lastDISPLAY(full)
  • Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.

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
seconds ← 200minutes ← seconds / 60rest ← seconds MOD 60DISPLAY(minutes)DISPLAY(rest)
  • Not directly available in AP CSP: Integer division (//) has no AP pseudocode equivalent. It was copied unchanged.

03Selection

AP selection puts the condition in brackets and the body in braces: IF(condition) { … } ELSE { … }. There is no ELSE IF, so each extra branch is nested inside the ELSE.

Examples5

3.1

If

IF(condition) followed by a braced block.

Java
int temp = 31;if (temp > 30) {    System.out.println("hot");}
AP CSP
temp ← 31IF(temp > 30){   DISPLAY("hot")}

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");}
AP CSP
mark ← 64IF(mark ≥ 50){   DISPLAY("pass")}ELSE{   DISPLAY("fail")}

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);
AP CSP
mark ← 72IF(mark ≥ 80){   grade ← "A"}ELSE{   IF(mark ≥ 70)   {      grade ← "B"   }   ELSE   {      IF(mark ≥ 60)      {         grade ← "C"      }      ELSE      {         grade ← "U"      }   }}DISPLAY(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");}
AP CSP
age ← 17hasTicket ← trueIF(hasTicket){   IF(age ≥ 18)   {      DISPLAY("enter")   }   ELSE   {      DISPLAY("adult needed")   }}ELSE{   DISPLAY("buy a ticket")}

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
DISPLAY("Temperature: ")temp ← INPUT()IF(temp < 0){   DISPLAY("freezing")}ELSE{   IF(temp < 15)   {      DISPLAY("cold")   }   ELSE   {      DISPLAY("warm")   }}

04Loops

AP has REPEAT n TIMES, REPEAT UNTIL(condition) and FOR EACH item IN list. REPEAT UNTIL stops when its condition is true, which is the opposite of while, so the condition is flipped. A counting loop that uses its counter becomes a REPEAT UNTIL with a counter variable.

Examples8

4.1

Count from 0 to n − 1

The counter is used inside the loop, so it becomes a counter variable with REPEAT UNTIL(i ≥ n). If the counter were unused you would get REPEAT n TIMES.

Java
int n = 5;for (int i = 0; i < n; i++) {    System.out.println(i);}
AP CSP
n ← 5i ← 0REPEAT UNTIL(i ≥ n){   DISPLAY(i)   i ← i + 1}

4.2

Count with a step

A stepped loop becomes REPEAT UNTIL with the counter increased by the step.

Java
for (int i = 0; i < 20; i += 5) {    System.out.println(i);}
AP CSP
i ← 0REPEAT UNTIL(i ≥ 20){   DISPLAY(i)   i ← i + 5}

4.3

Count down

Counting down becomes REPEAT UNTIL(i ≤ 0) with the counter decreased.

Java
for (int i = 10; i > 0; i--) {    System.out.println(i);}System.out.println("Lift off");
AP CSP
i ← 10REPEAT UNTIL(i ≤ 0){   DISPLAY(i)   i ← i - 1}DISPLAY("Lift off")

4.4

While with a condition

REPEAT UNTIL runs until its condition becomes true, so while balance < 200 becomes REPEAT UNTIL(balance ≥ 200).

Java
double balance = 100;int years = 0;while (balance < 200) {    balance = balance * 1.1;    years = years + 1;}System.out.println(years);
AP CSP
balance ← 100years ← 0REPEAT UNTIL(balance ≥ 200){   balance ← balance * 1.1   years ← years + 1}DISPLAY(years)

4.5

Input validation loop

Both become REPEAT UNTIL with the opposite condition: keep asking until the value is valid.

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);
AP CSP
DISPLAY("Mark (0-100): ")mark ← INPUT()REPEAT UNTIL(NOT(mark < 0 OR mark > 100)){   DISPLAY("Mark (0-100): ")   mark ← INPUT()}DISPLAY(mark)

4.6

Loop over every element of an array

FOR EACH name IN names matches Python's for-in directly.

Java
String[] names = {"Ali", "Bea", "Cai"};for (String name : names) {    System.out.println(name);}
AP CSP
names ← ["Ali", "Bea", "Cai"]FOR EACH name IN names{   DISPLAY(name)}

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);    }}
AP CSP
row ← 1REPEAT UNTIL(row ≥ 4){   col ← 1   REPEAT UNTIL(col ≥ 4)   {      DISPLAY(row * col)      col ← col + 1   }   row ← row + 1}

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);}
AP CSP
nums ← [4, -1, 7, 0, 3]FOR EACH n IN nums{   IF(n < 0)   {      continue;   }   IF(n = 0)   {      break;   }   DISPLAY(n)}
  • Not directly available in AP CSP: continue has no AP pseudocode equivalent. It was copied unchanged.
  • Not directly available in AP CSP: break has no AP 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
total ← 0i ← 1REPEAT UNTIL(i ≥ 11){   total ← total + i   i ← i + 1}DISPLAY(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
DISPLAY("Password: ")word ← INPUT()REPEAT UNTIL(word = "open"){   DISPLAY("Password: ")   word ← INPUT()}DISPLAY("Unlocked")

05Arrays & lists

AP lists start at index 1, not 0. The converter shifts every index for you (names[0] → names[1], names[i] → names[i + 1]). Length is LENGTH(list) and adding uses APPEND(list, value).

Examples7

5.1

Create with values

The list literal is kept, but scores[0] becomes scores[1] because AP lists start at 1.

Java
int[] scores = {12, 7, 19, 5};System.out.println(scores[0]);
AP CSP
scores ← [12, 7, 19, 5]DISPLAY(scores[1])

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.

Java
int[] counts = new int[5];System.out.println(counts[2]);
AP CSP
counts ← new int[5]DISPLAY(counts[3])
  • Not directly available in AP CSP: List/string repetition has no AP pseudocode equivalent. It was copied unchanged.

5.3

Read and update an element

Both indexes move up by 1: stock[1] becomes stock[2].

Java
int[] stock = {3, 8, 2};stock[1] = stock[1] - 1;System.out.println(stock[1]);
AP CSP
stock ← [3, 8, 2]stock[2] ← stock[2] - 1DISPLAY(stock[2])

5.4

Length

len() and .length both become LENGTH(list).

Java
int[] temps = {21, 25, 19, 23};System.out.println(temps.length);
AP CSP
temps ← [21, 25, 19, 23]DISPLAY(LENGTH(temps))

5.5

Last element

Because AP lists start at 1, the last element is simply list[LENGTH(list)].

Java
int[] temps = {21, 25, 19, 23};int last = temps[temps.length - 1];System.out.println(last);
AP CSP
temps ← [21, 25, 19, 23]last ← temps[LENGTH(temps)]DISPLAY(last)

5.6

2-D array

Both indexes move up by 1: grid[1][2] becomes grid[2][3].

Java
int[][] grid = {{1, 2, 3}, {4, 5, 6}};grid[1][2] = 0;System.out.println(grid[0][1]);
AP CSP
grid ← [[1, 2, 3], [4, 5, 6]]grid[2][3] ← 0DISPLAY(grid[1][2])

5.7

Add to a list

append() / add() become APPEND(list, value).

Java
ArrayList<Integer> evens = new ArrayList<>();for (int i = 1; i < 11; i++) {    if (i % 2 == 0) {        evens.add(i);    }}System.out.println(evens);
AP CSP
evens ← []i ← 1REPEAT UNTIL(i ≥ 11){   IF(i MOD 2 = 0)   {      APPEND(evens, i)   }   i ← i + 1}DISPLAY(evens)

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
values ← [3, 6, 9]i ← 1REPEAT UNTIL(i > LENGTH(values)){   values[i] ← values[i] * 2   i ← i + 1}DISPLAY(values[1])

06Strings

AP treats a string much like a list: LENGTH(word) and word[1] for the first character (1-based). Method calls such as upper() and joining with + are not part of AP pseudocode, so they are flagged.

Examples5

6.1

Length

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

Java
String word = "algorithm";System.out.println(word.length());
AP CSP
word ← "algorithm"DISPLAY(LENGTH(word))

6.2

One character

Characters are read with brackets, starting at 1, so word[0] becomes word[1].

Java
String word = "algorithm";char first = word.charAt(0);System.out.println(first);
AP CSP
word ← "algorithm"first ← word[1]DISPLAY(first)

6.3

Upper / lower case

AP has no case functions, so the method calls are copied and flagged.

Java
String city = "Paris";System.out.println(city.toUpperCase());System.out.println(city.toLowerCase());
AP CSP
city ← "Paris"DISPLAY(city.toUpperCase())DISPLAY(city.toLowerCase())
  • Not directly available in AP CSP: Method calls have no AP pseudocode equivalent. 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");}
AP CSP
DISPLAY("Password: ")password ← INPUT()IF(password = "secret"){   DISPLAY("Welcome")}ELSE{   DISPLAY("Wrong password")}

6.5

Joining strings with numbers

Joining and str() are not part of AP pseudocode, so they are flagged. Use separate DISPLAY calls instead.

Java
String name = "Sam";int score = 8;String message = name + " scored " + score;System.out.println(message);
AP CSP
name ← "Sam"score ← 8message ← name + " scored " + scoreDISPLAY(message)
  • Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. 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
DISPLAY("Word: ")word ← INPUT()DISPLAY(LENGTH(word))

07Subprograms

AP writes every subprogram as PROCEDURE name(params) { … }. A procedure that gives back a value uses RETURN(expression).

Examples5

7.1

Procedure with a parameter

The procedure body goes in braces and is called by name.

Java
public class Main {    static void greet(String name) {        System.out.println("Hello " + name);    }​    public static void main(String[] args) {        greet("Kim");    }}
AP CSP
PROCEDURE greet(name){   DISPLAY("Hello " + name)}greet("Kim")
  • Not directly available in AP CSP: String concatenation has no AP pseudocode equivalent. It was copied unchanged.

7.2

Function returning a value

return becomes RETURN(…).

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));    }}
AP CSP
PROCEDURE area(width, height){   RETURN(width * height)}DISPLAY(area(4, 6))

7.3

Function with no parameters

A function with no parameters keeps its empty brackets.

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);    }}
AP CSP
PROCEDURE getMark(){   DISPLAY("Mark: ")   mark ← INPUT()   RETURN(mark)}result ← getMark()DISPLAY(result)

7.4

Procedure that changes an array

The list is passed in; its indexes are shifted to start at 1 inside the procedure too.

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]);    }}
AP CSP
PROCEDURE reset(nums){   i ← 1   REPEAT UNTIL(i > LENGTH(nums))   {      nums[i] ← 0      i ← i + 1   }}data ← [4, 5, 6]reset(data)DISPLAY(data[1])

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));    }}
AP CSP
PROCEDURE factorial(n){   IF(n ≤ 1)   {      RETURN(1)   }   RETURN(n * factorial(n - 1))}DISPLAY(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
PROCEDURE larger(a, b){   IF(a > b)   {      RETURN(a)   }   RETURN(b)}DISPLAY(larger(3, 8))

08Random numbers

AP has RANDOM(a, b), which gives a whole number from a to b inclusive, like Python's randint.

Examples1

8.1

Dice roll (1–6)

randint(1, 6) becomes RANDOM(1, 6). Java nextInt(6) gives 0–5, so it becomes RANDOM(0, 5) + 1.

Java
Random rand = new Random();int roll = rand.nextInt(6) + 1;System.out.println(roll);
AP CSP
roll ← RANDOM(0, 5) + 1DISPLAY(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
n ← RANDOM(0, 99) + 1IF(n > 50){   DISPLAY("high")}ELSE{   DISPLAY("low")}

09Complete programs

These are the standard algorithms examiners ask for. Watch the list indexes: the converter keeps the counter starting at 0 and adds 1 whenever it reads the list.

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);
AP CSP
marks ← [56, 78, 91, 64, 70]total ← 0FOR EACH m IN marks{   total ← total + m}average ← total / LENGTH(marks)DISPLAY(total)DISPLAY(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);
AP CSP
temps ← [18, 24, 21, 27, 19]highest ← temps[1]i ← 1REPEAT UNTIL(i ≥ LENGTH(temps)){   IF(temps[i + 1] > highest)   {      highest ← temps[i + 1]   }   i ← i + 1}DISPLAY(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);
AP CSP
marks ← [45, 82, 67, 39, 90]passes ← 0FOR EACH m IN marks{   IF(m ≥ 50)   {      passes ← passes + 1   }}DISPLAY(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);}
AP CSP
data ← [5, 2, 9, 1, 7]n ← LENGTH(data)i ← 0REPEAT UNTIL(i ≥ n - 1){   j ← 0   REPEAT UNTIL(j ≥ n - 1 - i)   {      IF(data[j + 1] > data[j + 2])      {         temp ← data[j + 1]         data[j + 1] ← data[j + 2]         data[j + 2] ← temp      }      j ← j + 1   }   i ← i + 1}FOR EACH x IN data{   DISPLAY(x)}

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
nums ← [8, 3, 11, 5]lowest ← nums[1]i ← 1REPEAT UNTIL(i ≥ LENGTH(nums)){   IF(nums[i + 1] < lowest)   {      lowest ← nums[i + 1]   }   i ← i + 1}DISPLAY(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
word ← "banana"count ← 0i ← 1REPEAT UNTIL(i > LENGTH(word)){   IF(word[i] = "a")   {      count ← count + 1   }   i ← i + 1}DISPLAY(count)