Quick Index
Overview


Pseudocode means "almost-code". It is user-friendly (developer-friendly) human readable code.

The primary purpose of pseudocode is to convey/share logical ideas.

Generally, pseudocode is not run. However, we do have a algorithm lab available -- it is for playing and experimenting with algorithms -- not for real coding -- its use is optional

This page describes the syntax (rulebook) for the pseudocode we will use. It is example driven.

NOTE WELL --Remember that the primary purpose of pseudocode is to "convey logical ideas" and not to provide perfect (bug-free) syntax.

Also see Do We Worry About Errors in Pseudocode

Intrinsic (Provided) Features


We will assume that the function "println" is available -- we may call it anytime, from any function.
let a = 10
println('Hello')
println('a: ' + 10)


Variables



We use the keyword "let" to declare the variable and assign a value to the variable on the same line using the assignment ("=") operator.
let x = 5
let name = "Asha Zandaski"
let area = this.getArea()

_hiddenSource_

//Try It
let name = "Asha Zandaski"
println(name);
//Run your experiments here
We can optionally declare all are variables before their usage as we do on the highlighted line.
let x, name, area
x = 5
name = "Asha Zandaski"
area = this.getArea()

_hiddenSource_

//Try It
let name;
name = "Asha Zandaski"
println(name);
//Run your experiments here
Just a slight variation from the previous -- we can use the keyword "var"
var x, name, area
x = 5
name = "Asha Zandaski"
area = this.getArea()

_hiddenSource_

//Try It
var name;
name = "Asha Zandaski"
println(name);
//Run your experiments here

Operators



Standard oo comparison operators as shown.

See next section about "Equality Gotcha".
elem1.equals(elem2)		//object equality
num1 == num2			//prim value equality/equals
num1 != num2			//prim value not equal

x > y				//greater than
x >= y				//greater than or equal to
x < y				//less than
x <= y				//less than or equal to

a.equals(b) ? 'Test Passed' : 'Test Failed'	//ternary

_hiddenSource_

//Try It
let elem1, elem2, elem3;
elem1 = 10;
elem2 = 10;
elem3 = 20;
println(elem1 + " " + elem2 + " " + elem3);
println(elem1.equals(elem2));
println(elem1.equals(elem3));
println(!elem1.equals(elem3));
//Run your experiments here
We may use primitives in examples (for simplicity), but in reality our structures will use objects.

The "==" and "!=" operators only work for primitives.

As shown, it is safer to use "equals" which works for either primitives or objects.
// In real code, use "equals" and "!equals" like this:
let boolean1 = a.equals(b)
let boolean2 = !a.equals(b)
// Do not either of "==" or "!="
let boolean1 = a == b
let boolean2 = a != b

/*Exception to this rule -- only if you are certain
that both of your operands will be primitives, then
you could (optionally) use "==" or "!="
(but "equals" will work also).*/
//if it is known that both operands are primitives, this is okay:
let isEqual = index1 == 10
// This is also okay
let isEqual = index1.equals(10)
These logical operators (as shown) are pretty standard in oo
(x > y) && (x > 10)  //"&&" is the "and" operator
                     //checks if both left and right are true
 
(x > y) || (x > 10)  //"||" is the "or" operator
                     //checks if either left or right are true
 
!(0==1)              //"!" is the "not" operator -- inverts (flips)
                     // (example here would be true)

_hiddenSource_

//Try It
let x, y;
x = 20;
y = 15;
println((x > y) && (x > 10));
//Run your experiments here
Here is a listing of the arithmetic operators
x = a + b;		//addition
x = a - b;		//subtraction
x = a * b;		//multiplication
x = a / b;		//division
x = a % b;		//modulus (remainder)
x++;			//shorthand for "x = x + 1"
x--;			//shorthand for "x = x - 1"

_hiddenSource_

//Try It
let x, a, b;
a = 20;
b = 15;
println("a: " + a);
println("b: " + b);
println("a % b: " + a % b);
//Run your experiments here

Arrays



Overview


The pseudocode supports two array (collection) types:

Fixed array -- fixed in size -- can not append elements
Dynamic array - dynamic in size -- can add elements

note -- we may see/use a variety of names for arrays, such as list, collection, coll, ...

Fixed Array


Hello, I am a fixed array. My size is fixed.

I do not support appending/adding/removing elements (i.e., I cannot change my size). See my friend "dynamic" (below).

Construct a fixed array of size 2.
let array = Array.newFixed(2);
Set two elements at fixed positions 0 and 1 (zero-based indexes).
let array = Array.newFixed(2);
//At index=0, set value 10
array[0] = 10;
//At index=1, set value 20
array[1] = 20;
println(array);
Get elements at specified index.
let array = Array.newFixed(2);
array[0] = 10;
array[1] = 20;
//Get element at index=0, then element at index=1
println(array[0]);
//or
println(array.get(0));


Dynamic Array


Nice to meet you. I am a dynamic array.

I support appending/adding elements and removing (i.e., changing my size).

Construct a dynamic array. Initially size is 0 (array is empty). But we can easily append/add elements (see next).
let array = Array.newDynamic();
Add four elements by simply calling the "add" method.
let array = Array.newDynamic();
array.add(40);
array.add(30);
array.add(20);
array.add(10);
println(array);
Here is a convenient way to initialize an array with given data.
let a = [2, 4, 6, 8];
println(a);
We'll routinely need the size of an array in our algorithms. We can get that via length or size(), as shown.
let a = [2, 4, 6, 8];
println(a.length);
println(a.size());

Control (Conditional) Logic


Pseudocode code for the "If statement" likely looks familiar.

 if (CONDITION) {
}

The code in the code block "{}" evaluates only if the if condition is true.
if (a > b) {
	println('yep, a is larger')
}

_hiddenSource_

//Try It
let a = 100;
let b = 99;
if (a > b) {
	println('yep, a is larger')
}
//Run your experiments here
Pseudocode code for the "If-Else statement" likely looks familiar.

 if (CONDITION) {
} else {
}

The code in the code block "{}" following the "if" statement evaluates only if the if condition is true, otherwise the code block "{}" following the "else" statement evaluates.
if (a > b) {
	println('a is larger')
} else {
	println('b is larger')
}

_hiddenSource_

//Try It
let a = 100;
let b = 101;
if (a > b) {
	println('a is larger')
} else {
	println('b is larger')
}
//Run your experiments here

Iteration (Looping)



We have a few options, shown below, for iteration and looping.

This is a simple way to iterate (incrementing a loop var)
  • Initialize loop var 'i'
  • Loop while 'i' < len
  • Increment 'i'

In the code block "{}" we have scope (visibility) to the loop var 'i'.
/** Iterates using while loop and index */
function printAll(list) {
	let len = list.length

	
1
let i = 0 while (
2
i < len) { let eachElem = list[i] println(eachElem)
3
i++ } } //Try It let myList = ['Asha', 'Chin', 'Kofi']; printAll(myList);
  • Loop over all elements in var 'list'
  • And for each loop, let var 'eachElem' equal the next elem.

In the code block "{}" we have scope (visibility) to the loop var 'i'.
/** Iterates over objects (when index is not needed) */
function printAll(list) {

	
1
for (let
2
eachElem of list) { println(
3
eachElem) } } //Try It let myList = ['Asha', 'Chin', 'Kofi']; printAll(myList);
  • Initializer -- runs (once) before first loop starts
  • Condition -- checks before each loop (continues looping if true)
  • Incrementer -- runs after each loop

In the code block "{}" we have scope (visibility) to the loop var 'i'.
/** Iterates using while loop and index (abbreviated syntax) */
function printAll(list) {
	for (
1
let nextIndex = 0;
2
nextIndex < list.length;
3
nextIndex++) { let nextElem = list[nextIndex] println(nextElem) } } //Try It let myList = ['Asha', 'Chin', 'Kofi']; printAll(myList);

Functions



Simple One-Line Functions


When functions are simple enough to be coded on one line, the return value is implied (as shown below).

Functions perform some sort of task. They receive zero-to-many inputs and generate zero-or-one outputs.
Functions are explained here...
Our pseudocode will use a user-friendly (developer-friendly) syntax for functions demonstrated in the following examples.
Here is a function where the input is a number (primitive) and the output is a number.

This function simply triples the input, and returns the result
//Outputs the triple of input x
let tripleNumFct = (x) => 3 * x

//Try It
let x = 10;
let y = tripleNumFct(x);
println(y);
Here is a function where the input is an object (an array) and the output is an element from the array.

This function returns the first element in the input array.
let getFirstFct = (array) => array.get(0);

let array = ['A++', 'A', 'A-'];
let result = getFirstFct(array);
println('Result is ' + result);


Multi-Line Functions


When functions are more complex, we can code them on multiple lines. When then need to explicitly use the return keyword (as shown below).

Here is a function where the input is an object (an array) and the output is an element from the array.

This function returns the first element in the input array.
let getFirstFct = (array) => array.get(0);

let array = ['A++', 'A', 'A-'];
let result = getFirstFct(array);
println('Result is ' + result);

OO


Our pseudocode will use a common oo syntax:


Object types (classes) are pseudocoded as shown.
class Foo {
}
If there is object initialization to be performed (e.g. "ivars") when the object is constructed, we do it in the "initialize" instance method. We assume this method is always called once at the time the object is constructed.
initialize() {
	// Initialize this object
	this.contents = [];
	this.position = 0;
}
We will use "this" in the typical oo way -- "this" refers to the current object (the object that contains the algorithm/code)
this.println()
let width = this.width
let area = this.computeArea()
We access ivars in the usual way using the "dot operator"
//get property from "this" object (i.e., the current object)
width = this.width
//get property 'length' from object 'bigList'
len = bigList.length
We'll send messages in the usual way using the "dot operator"

Note: We prefer to send messages rather than using direct instance variable access (we'll learn more about this soon).
bigList.reverse()
this.setWidth(10)
this.computeResult()


Miscellaneous


Trailing semi-colons are optional
foo.println()			//okay without ';'
foo.println();		//okay with ';'
To throw an error (exception) use the keyword "throw" followed by a space and then the error message.
throw "index out of range"