Download presentation
Presentation is loading. Please wait.
1
Week 6: Arrays 1
2
Loops are great But, without a way to talk about a group of values, we can’t get the full potential out of a loop Enter: the array 2
3
An array is a homogeneous, static data structure homogeneous means that everything in the array is the same type: int, double, String, etc. static (in this case) means that the size of the array is fixed when you create it 3
4
The args variable passed into the main() method is an array of type String This array has a set number of String s (maybe zero) that you can use as input to your program Now, we are giving you the ability to create and manipulate your own arrays 4
5
To declare an array of a specified type with a given name : Example with a list of type int : Just like any variable declaration, but with [] type[] name; int[] list; 5
6
When you declare an array, you are only creating a variable that can reference an array At first, it references nothing, also known as null To use it, you have to create an array, supplying a specific size: This code creates an array of 100 int s int[] list; list = new int[100]; 6
7
As you have seen with args, you can access an element of an array by an index into it, using square brackets and a number Once you have indexed into an array, that variable behaves exactly like any other variable of that type You can get values from it and store values into it Indexing starts at 0 and stops at 1 less than the length list[9] = 142; System.out.println(list[9]); 7
8
When you instantiate an array, you specify the length Sometimes (like in the case of args ) you are given an array of unknown length You can use its length member to find out int[] list = new int[42]; int size = list.length; System.out.println(“List has “ + size + “ elements”); //prints 42 8
9
When you create an int, double, char, or boolean array, the array is automatically filled with certain values For other types, including String s, each index in the array must be filled explicitly TypeValue int0 double0.0 char‘\0’ booleanfalse 9
10
Explicit initialization can be done with a list: Or, a loop could be used to set all the values: String[] days = {“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”}; int[] numbers = new int[100]; for(int i = 0; i < numbers.length; i++) numbers[i] = i + 1; 10
11
An array takes up the size of each element times the length of the array Each array starts at some point in computer memory The index used for the array is actually an offset from that starting point That’s why the first element is at index 0 11
12
Suppose that we have an array of type int of length 10 Java decides what address in memory is going to be used, but let’s say it starts at 524 1243-967890-2323106 0 1 2 3 4 5 6 7 8 9 524 528 532 536 540 544 548 552 556 560 Addresses Indexes 12
13
Arrays are a fixed size list of a single kind of data A for loop is ideal for iterating over every item and performing some operation for loops and arrays will crop up again and again Of course, a while loop can be used with an array, but it is not used as often 13
14
Imagine that we have an array of int s called list Let’s use a for loop to sum up those int s Super easy! We don’t even need to know how big the array is ahead of time int sum = 0; for( int i = 0; i < list.length; i++ ) sum += list[i]; 14
15
Last week, we showed you how to add a set of numbers together as they were input by a user Although this is a useful technique, not every operation is possible We can find the sum or the average of the numbers because we only need to see the numbers once What operation needs to see the numbers more than once? 15
16
Variance is a measurement of how spread out numbers are from their mean To calculate it, you have to calculate the mean first The formula is: Where N is the number of elements, x i is the i th element, and is the mean 16
17
Given an array of doubles called number, here’s the code for finding their variance double average = 0; double variance = 0; double temp; for( int i = 0; i < number.length; i++ ) average += number[i]; average /= number.length; for( int i = 0; i < number.length; i++ ) { temp = number[i] – average; variance += temp*temp; } variance /= number.length; 17
18
We can represent a deck of cards as an array of 52 items One easy way is to make each item a String giving the name of the card 18
19
Swapping the values of two variables is a fundamental operation in programming It is going to become more important in arrays because the order of values could be important The simplest way to swap two variables involves using a third variable as a temporary location 19
20
Here is an example of swapping two String s indexed i and j in an array of String s called moniker int i = StdIn.readInt(); int j = StdIn.readInt(); String temp; temp = moniker[i]; moniker[i] = moniker[j]; moniker[j] = temp; 20
21
Using the swap code, we can do a random shuffling of a deck To do so, we go through each element of the array, and randomly swap it with any of the later elements for( int i = 0; i < n; i++ ) { exchange = i + (int)(Math.random() * (n - i)); temp = deck[i]; deck[i] = deck[exchange]; deck[exchange] = temp; } 21
22
Searching through an array is an important operation The simplest way to do so is just linear search: check every element in the array Searching and sorting are really keys to all kinds of problems We’ll cover both topics in depth in a few weeks 22
23
23
24
Remember, you get no initialization with arrays of String s If you try to access a non-existent element, the world will explode String[] stuff = new String[50]; String s = stuff[42]; // works fine int size = s.length(); // destroys world 24
25
Accessing an element of an array that doesn’t exist will also kill your program int[] numbers = new int[100]; numbers[103] = 5; //crash System.out.println( numbers[-3]);//crash System.out.println( numbers[99]);//okay for( int i = 0; i <= 100; i++ ) numbers[i] = i; //crashes when i = 100 25
26
Just as it is possible to make a one- dimensional list out of a single data type, it is also possible to make a table out of one data type We can extend the arrays you know to have two dimensions with very similar syntax 26
27
To declare a two dimensional array, we just use two sets of square brackets ( [][] ): Doing so creates a variable that can hold a 2D array of int s As before, we still need to instantiate the array to have a specific size: int [][] table; table = new int[5][10]; 27
28
Like matrices, we usually visualize the first dimension as the rows and the second dimension as the columns 0 1 2 3 4 5 6 7 8 9 0123401234 Second Dimension First Dimension 28
29
Let’s write a little code to put data into the table int [][] table = new int[5][10]; int label = 1; for( int i = 0; i < 5; i++ ) for( int j = 0; j < 10; j++ ) { table[i][j] = label; label++; } 29
30
The result of that code is: 0 1 2 3 4 5 6 7 8 9 0123401234 Second Dimension First Dimension 30
31
The ability to represent 2D data opens up lots of possibilities We could store: A chessboard An image (where each number represents the color of a pixel) A game of battleship Or something even more interesting… A matrix! 31
32
I’m sure you’ve seen matrices before Still, here’s a refresher: m rows n columns 32
33
Addition can be done between two m x n matrices but not between matrices with mismatching dimensions Just add the corresponding locations You can also multiply an m x k matrix called A by a k x n matrix called B: only the common dimension must match The result is an m x n matrix where the element in row i, column j is 33
34
We could represent a chessboard as an 8 x 8 array of char s Use the following encoding: ‘P’ = pawn ‘N’ = knight ‘B’ = bishop ‘R’ = rook ‘Q’ = queen ‘K’ = king Use upper case characters for black pieces and lower case characters for white ones 34
35
Imagine there is a pawn randomly set on the board and a queen of the opposite color on the board Write a program to see if the queen can capture the pawn in the next move Q p 35
36
Find the row and column location of both the queen and the pawn The pawn is in danger if: 1. The queen and the pawn have the same row 2. The queen and the pawn have the same column 3. The queen and the pawn are on the same diagonal 36
37
I lied to you There are no such things as multidimensional arrays They are all actually just arrays of arrays (of arrays…) You are not required to create all of the dimensions at one time 37
38
You could create each dimension separately and even specify different sizes For example: int [][] pharma = new int[5][]; for( int i = 0; i < 5; i++ ) pharma[i] = new int[i + 1]; 38
39
The resulting array will look like this: 0123401234 0 1 2 3 4 Columns Rows 39
40
First of all, be warned that if you access an element that an array doesn’t have, your program will still crash Ragged arrays do allow you to save some space Imagine if some rows needed 10 elements and others needed 1,000,000 Usually, there’s no good reason to use ragged arrays, but sometimes there is…. 40
41
It doesn’t have to stop at 2 dimensions! You can have 3 or more Here’s an example with 3 dimensions: int [][][] rubiksCube = new int[3][3][3]; int count = 1; for( int i = 0; i < rubiksCube.length; i++ ) for( int j = 0; j < rubiksCube[i].length; j++ ) for( int k = 0; j < rubiksCube[i][j].length; k++ ) { rubiksCube[i][j][k] = count; count++; } 41
42
It looks like whatever you want it to You can visualize it in 3D if you want There are other techniques It’s just a way to store data It doesn’t actually look like anything inside the computer 42
43
Sometimes you have data categorized in several different ways For example, Purdue might keep some statistics according to Year, Gender, and Race 0 – Freshman 1 – Sophomore 2 – Junior 3 – Senior Perfect candidate for a 3D array 0 – Male 1 – Female 0 – African American 1 – Asian 2 – Caucasian 3 – Other 43
44
Too many brackets Too much stuff Total size used is the product of the length of all the dimensions 100 x 100 x 100 = 1,000,000 Hard to visualize, hard to imagine Up as high as 4 is sometimes useful Don’t go beyond 3 on a regular basis 44
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.