The Coder's Handbook

Arrays

WHAT IS AN ARRAY?

An array is a type of data structure used to store information. Data structures are used to organize, arrange, and access collections of information.


Arrays are the most basic data structures. Take a moment to look at the diagram above. Take note of the following:

  • The array has a length of 10

  • The index positions start at 0 and end with 9

  • Thus the final index is equal to length - 1


CREATING AN ARRAY

When you want to create an array, you'll need to do three things:


Declaration

  • Works like any other variable

  • Usually at the top of your program


Initialize The Array


  • Need to manually allocate memory

  • If you skip this step, you'll get a NullPointerException

  • Usually done in setup()


Initialize Each Element

  • Gives the actual data starting values

  • You can skip this step if you're okay with everything starting at zero

Example

int[] numbers;


void setup()
{

numbers = new int[200];


for(int i = 0; i < numbers.length; i++)

{

numbers[i] = (int) (Math.random() * 10);

}

}




USING ARRAYS

Accessing an element

    • To access an element, you will reference it by its index position:

System.out.println(numbers[3]);

Set an element

    • To set an element, you do the same thing but on the left hand side:

numbers[3] = 74;

Get the length

    • To get the number of elements in an array, you use the length property.

if(numbers.length < 5)

TWO DIMENSIONAL ARRAYS

Two dimensional arrays are not officially part of the course this year, but I've provided a quick summary here for students who want to explore them!

Rows and Columns

    • A row is a horizontal line of data. Think the motion of rowing a boat.

    • A column is a vertical line of data. Think about the structure of a column holding up a building.

    • Rows are listed before columns when accessing an index position.

Syntax

    • When using a two dimensional array, we simply double everything!

    • Most commonly, we'll make variables or constants to keep track of rows and columns to help our code be more readable.

Examples

final int ROWS = 100;

final int COLS = 50;

char [] grid = new char[ROWS][COLS]


for(int i = 0; i < COLS; i++)

{

for(int j = 0; j < ROWS; j++)

{

grid[i][j] = "-";

}

}


println(grid[32][45]);

RESOURCES

Chapter 9 - Arrays (p163)

Overview of Arrays in One Video

9.1 - What is An Array (Concepts)

9.2 - Coding an Array

9.3 - Using Objects with an Array
(This includes new stuff we haven't learned)

9.4 - Using Loops an Array of Objects
(This includes new stuff we haven't learned)