Download presentation
Presentation is loading. Please wait.
1
Chapter 9 Arrays
2
What is an Array An array is a special variable, which can hold a collection of elements of the same type. Examples: A list of colors A list of objects, such as rain drops or cars A list of players in a game A sequential list of numbers to associate with other variables such as x, y, w, h, color, etc.
3
Characteristics of Arrays
Arrays start with 0. Arrays have a fixed size. Each element in an array has a unique position, in which the order is crucial. Each index/position of an array is matched with an element. E.g. array of your siblings you might be #2. The size can be: - A number - A variable of int type - An expression that calculates an integer
4
Declaring and Initializing Arrays
Declaring: int [] myArray; String [] myWord = new String[6]; Declaring and initializing with values : float[] myNums = { 1.0, 3.2, 6, 9.5};
5
…from processing.org/tutorials/arrays, an easier way to remember array declarations
// Declare int[] data; // Create data = new int[5]; // Assign data[0] = 19; data[1] = 40; data[2] = 75; data[3] = 76; data[4] = 90; // Declare & create int[] data = new int[5]; // Assign data[0] = 19; data[1] = 40; data[2] = 75; data[3] = 76; data[4] = 90; // Declare, create, assign int[] data = { 19, 40, 75, 76, 90 };
6
Examples of specifying size
color [] swatches = new color[4]; int [] storeLoc = new int [12]; int cities = 5; string [] mycities = new string [cities]; int [] family = new int [siblings+parents]
7
In summary, 3 ways to fill with value (initialize)
Hard code the values in each spot. Type out a list in curly brackets separated by commas. Iterate through the elements in an array. See next slide…
8
Table: Three ways to initialize
Hard code the values in each spot String [] stuff = new String [4]; stuff[0] = "Buick"; stuff[1] = "Nissan"; stuff[2] = "Toyota"; stuff[3] = "Ford"; Type out a list in curly brackets separated by commas. String [] siblings = {"Ernest", "Mary", "Therman"}; The above two methods are inefficient for large arrays. The third option is most widely used. Also, there are more advanced ways such as filling with data from a text file. Iterate through the elements in an array. This also allows you to access each index value. for(int i = 0; i < stuff.length; i++ { }
9
Accessing elements in Arrays
Several ways… Iterating through each element is one of them. See examples 9-5, 9-6, and 9-7. (remix)
10
Create a Bar Chart Look at bar chart example at: Then remix your own way.
11
Time for Fun Programming again
#54 A bit of a remix with names and descriptions of computer company founders
12
Do It Yourself: Create a String array with about 5 names of family members. Iterate through each. If time permits, use a for() to place a rectangle around each name. println() or text() to see results (See solution at moorec.people.cofc.edu/fam.txt)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.