Link Search Menu Expand Document

Pseudocode Reference

Table of Contents

  1. General rules
  2. Syntax
    1. Functions
    2. Conditionals
    3. Iteration
  3. Data Structures
    1. Arrays and Lists
    2. HashSets

General rules

  • Proper pseudocode has two properties:
    • Pseudocode should allow you to focus only on the logic
    • Pseudocode should include enough information to write actual code
  • You should describe the problem the algorithm solves by defining Input and Output
  • When the code is straightforward, translate it directly
    • Example: return n * factorial(n-1)
    • Example: maxSoFar = max(maxSoFar, el)
  • When the code is harder to parse, switch to English
    • Example: maxSoFar = -infinity instead of int maxSoFar = Integer.MIN_VALUE;
    • Example: for each element el in L instead of int i = 0; i < list.size(); i++
    • Example: if x is odd instead of if (x % 2 == 1)
  • You don’t need to declare the types of variables within an algorithm, but you should define exactly the data structures you use
    • Do: seen = new hashset of integers
    • Don’t: int x = 4 (the int is implied)
  • Avoid “Java-isms”
    • Do: return i, j
    • Don’t: return new int[] {i, j}

Syntax

Functions

OperationPseudocodeJava
declaration
  algorithm fib
    Input: non-negative integer n
    Output: the nth fibonacci number
   
public static int fib(int n)
callssumOfSquares(3, 4)sumOfSquares(3, 4);
returnsreturn 4return 4;

Conditionals

OperationPseudocodeJava
if else
  if x is odd
    ...
  else
    ...
    
  if (x % 2 == 1) {
    ...
  } else {
    ...
  }
    

Iteration

OperationPseudocodeJava
elements
  for element el in Lst
    print(el)
    
  for(int i = 0; i < lst.size(), i++) {
    int el = lst.get(i);
    System.out.println(el);
  }
    
index
  for index i in Lst
    print(i)
    
  for(int i = 0; i < lst.size(), i++) {
    System.out.println(i);
  }
    
index (alt)
  for index i = 0, 1, 2, ... Lst.size()-1
    print(i)
    
  for(int i = 0; i < lst.size(), i++) {
    System.out.println(i);
  }
    
numbers
  for i = 1, 2, ..., n-1, n
    print(i)
    
  for(int i = 1; i <= n, i++) {
    System.out.println(i);
  }
    

Data Structures

Arrays and Lists

PseudocodeJava
  results = integer array of size 20
  otherResults = integer array of size inputArr.length
  results[2] = 4
      
  int[] results = new int[20];
  int[] otherResults = new int[inputArr.length];
  results[2] = 4;
      

HashSets

PseudocodeJava
  example1 = empty hashset of strings
  example1.add("foo")
  example1.add("bar")
  example1.contains("foo") // true
  example1.contains("baz") // false
      
  HashSet<String> example1 = new HashSet<>();
  example1.add("foo");
  example1.add("bar");
  example1.contains("foo");
  example1.contains("baz");