100 likes | 211 Views
Lecture 7: Arrays. Yoni Fridman 7/9/01. Outline. Back to last lecture – using the debugger What are arrays? Creating arrays Using arrays Examples Accessing arrays sequentially Accessing arrays arbitrarily. 7. 2. 8. 8. 9. 2. 5. 7. 4. What Are Arrays?.
E N D
Lecture 7: Arrays Yoni Fridman 7/9/01
Outline • Back to last lecture – using the debugger • What are arrays? • Creating arrays • Using arrays • Examples • Accessing arrays sequentially • Accessing arrays arbitrarily
7 2 8 8 9 2 5 7 4 What Are Arrays? • All of the variables we’ve used so far store a single value each. • What if we want to store a bunch of related values? • Example: A deck of cards. • An array is a structure that stores multiple values, all of which must be of the same type. • Each individual value is called an element of the array.
Creating Arrays • Declaring an array is the same as declaring any normal variable, except you need to add square brackets []. • For example, we would declare an array of ints like this: int[] deckOfCards; • Now deckOfCards can hold any number of ints, not just one. • Similarly, we can declare arrays of other types: • String[] classRoll; declares an array of Strings. • Problem: How many elements can the array hold?
Creating Arrays • Arrays are initially of length zero. • Before we use an array, we must allocate space for it (tell it how many elements we want it to have). • When you allocate space with the new keyword, all elements are given default values (0 for ints). • What happens if you try to use an array before allocating space for it? int[] deckOfCards; deckOfCards = new int[52]; OR int[] deckOfCards = new int[52];
7 2 8 8 9 2 5 7 4 7 8 4 5 1 2 6 3 0 Using Arrays • Like we saw with Strings, each element of an array has an index, starting from zero: Notice that an array with n elements has indices 0 through n-1. • So how do we use arrays? • To access the third array element, for example, we write deckOfCards[2]. • This now acts as a normal int variable.
Using Arrays • What will this example do? • Warning: Make sure you never try to access the nth element of an array that has n elements. • For example, deckOfCards[52] will give an out-of-bounds error. (Remember, the 52nd element is deckOfCards[51].) • This is our first example of a run-time error. • Note: To find the length of deckOfCards, for example, write deckOfCards.length. deckOfCards[3] = 7; deckOfCards[1] = deckOfCards[3]; System.out.println(deckOfCards[1]);
Accessing Arrays Sequentially • In many cases, you want to look at each array element, one at a time. • A for loop is perfect for this. • Code example: Summing the elements of an array. • Code example: Finding the largest element in an array.
Accessing Arrays Arbitrarily • Sometimes you want to access some elements of an array, but not others. Furthermore, you might not want to go in order. • Example: Counting cards.
Homework • Read: 13.1 (to end of p. 545)