1 / 11

Arrays

Arrays. Chapter 7 day 1. What is an array?. An array is a variable that collects a sequence of values of the same type. It is essentially a variable with one name, that sets aside multiple slots in memory to store multiple values of the same type.

pleasance
Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays Chapter 7 day 1

  2. What is an array? • An array is a variable that collects a sequence of values of the same type. It is essentially a variable with one name, that sets aside multiple slots in memory to store multiple values of the same type. • Each slot has an index just like a string. The indexes start at 0 and end at 1 less than the length.

  3. For example • An integer array called values would look like this:

  4. Declaring an array • An array can be of any type (primitive, or object) • To declare an array, put [ ] after the type • Ex: int[ ] values; //declares an integer array called values Dice [ ] die; //declares a Dice array called die

  5. Declaring an array • Before using an array, you must establish its size • Ex: int[] values; values = new int[10]; Or int[]values = new int[10]

  6. If you are prepared to initialize right away • You can initialize and declare at the same time int[] values = {2,12,33,15,16,47} Note: Once size is set it cannot be changed!!

  7. Array variables store a reference!!! • Much like object variables, Arrays store a reference or memory address! Keep that in mind!! int[] scores = {2,4,6,8,10}; int[]values = scores; How many arrays are there?

  8. Length and index • The length of an array is a constant, not a method. To access the length you type name.length with no () • To access a specific value put the index in [ ] count[2] += 4;

  9. Using a for loop to initialize arrays int [] count = new int[13]; for(inti=0;i<count.length;i++) { count[i]=0; }

  10. Arrays can be passed as parameters • This is a valid method header public void fillArray(int[] values)

  11. Homework • Create a program called DiceArray. Add the Dice class to your project. Write a short program which will create two dice objects, roll the dice 1000 times, and will count and display how many times each value 2-12 was rolled. Use an array

More Related