Arrays
An array stores many pieces of data but in the same variable. For example I could save the marks for 5 students in an array like:
This array has 5 elements (note that you usually start counting at 0 with arrays!) but they all have just one variable name (studentMarks). To refer to a specific mark you place the index of the mark after the variable name, usually in brackets. For example, you would refer to the mark of 84 as:
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
# array (or list) index
studentMarks[3]
Arrays are an important programming concept because they allow a collection of related objects to be stored within a single variable. To declare an array, you usually must specify how many elements will be in the array during the declaration. This is because the compiler needs to reseve the required memory inside the the computer to stare all these variables. (There are ways to store groups of data where the size will change during the running of the program and we will get to them.)Here we are declaring the variable studentMarks and allowing 5 items in it:
// array index
int studentMarks[5];
// array index
int studentMarks[5];
// array index
int[] studentMarks = new int[5];
// array index
var studentMarks[5]int
// array index
int [] studentMarks = new int[5];
// array index
let studentMarks = new Array(5)
# array (or list) index
studentMarks = []
Once you have an array, you will need to loop over it to add items to it or to see what the values are. It is usually a bad idea to Hard Code your loop ending point to a value. An array knows how many elements are in it and you should always use this. If someone changes the size of the array in the declaration, then no othe code will have to be changed.
Here is a code example of creating an array, placing values into it and then reading data out of it: