Arrays

An array is a list of variables of any type.

Each “cell” of the array is identified by an index number representing its position

The first element in the array is [0], the second element is [1], and so on.

There are many ways to create arrays unlike variables they must be created with the keyword new.

Declaration

// A list of 4 floating point numbers
float[] scores = new float[4]; 

// You can use an expression to specify size
Spaceship[] ships = new Spaceship[num*2 + 3]; 

Initialization

// Initializing elements of an array one at a time

int[] stuff = new int[3];
stuff[0] = 8; // The first element of the array equals 8
stuff[1] = 3; // The second element of the array equals 3
stuff[2] = 1; // The third element of the array equals 1

//Initializing elements of an array all at the same time

int[] arrayOfInts = {1,5,8,9,4,5};
float[] floatArray = {1.2,3.5,2.0,3.4123,9.9};

//using for loops

float[] values = new float[1000];

int n = 0;
for(int i = 0; i<1000; i++) {
  values[i] = random(0,10);
 }

Accessing element

//starting from the array above
println(values[3]);

//printing all the values
for(int i = 0; i<1000; i++) {
println(values[i]);
}

//or, if I don't know the length
for (int i = 0; i < values.length; i ++ ) {
  println(values[i]);
} 

Array functions

String[] sa1 = { "OH", "NY", "CA"}; 

//Append expands an array by one element and adds data to the new position.
String[] sa2 = append(sa1, "MA"); 

println(sa2);

//copy - arrays can't be copied like variables, they have their own function
String[] north = { "OH", "IN", "MI" };
String[] south = { "GA", "FL", "NC" };
arrayCopy(north, south);
println(south);

//concatenation
String[] sa2 = { "KY", "IN", "MA"};

String[] sa3 = concat(sa1, sa2);
println(sa3);

//splice inserts a value or an array of values into an existing array 
//in a certain position
a = splice(a, "KY", 1);  // Splice one value into an array
println(a);

//subset extracts elements from an array and puts it into a new one
String[] sa4 = subset(sa1, 1);
String[] sa5 = subset(sa1, 2, 3);

//sorting
float[] a = { 3.4, 3.6, 2, 0, 7.1 };
a = sort(a);
println(a);

/*
Sorts an array of numbers from smallest to largest, or puts an array of words in alphabetical order. The original array is not modified; a re-ordered array is returned.
*/

Exercises

Starting from this array:
int[] nums = {5,4,2,7,6,8,5,2,8,14};

* Square each number ((i.e., multiply each by itself)
* Extract a random number within the array
* Calculate the sum of all the numbers.
* Add to each number the number that follows in the array. Skip the last value in the array.

Posted in

Post a comment