arrays - Arrays Motivation for Arrays Suppose we want to...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Arrays Motivation for Arrays Suppose we want to store 100 values entered by the user. Knowing what we do so far, we would have to declare 100 different variables to hold the information. This would be doable, but it would be a giant pain. Next, suppose we want to store a bunch of values entered by the user, but we don’t know how many – it might be 10, it might be 100,000. We could try to declare 100,000 variables, just in case, but even this wouldn’t work if the user decided to store more than that. To solve this problem, we need a convenient to store a list of values. Furthermore, we want this list to be able to hold any number of values, depending on the user’s needs. Java has a feature called an array that is used to store a variable number of elements. Single-Dimensional Arrays A single-dimensional array stores a list of elements of the same type. We can make this list be any size that we want. Declaration Here’s how to declare an array: type[] name; This will declare an array called name that can hold elements of type type . For example, to declare an array of int s called nums : int[] nums; Now, we need to create space for the array. Before we can add any elements to the array, we need to specify the number of slots we want to reserve. Here’s how: name = new type[size]; Here, name is the name of the array, type is the type of elements the array holds, and size is a positive integer that specifies how many slots we want in the array. size can be either a constant value (like 10) or an int variable. Here’s how to make our nums array have 10 slots: nums = new int[10]; We can also declare an array and reserve space for it on the same line: int[] nums = new int[10];
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Initialization Now that we have space for the array elements, we can start putting values in the array. Here’s how to access array elements: name[index] This accesses the element in array name at index index . C# array indices start at 0 and go up to size -1 (where size is the number of slots we reserved for the array). For example, here’s how we’d set the first element in the nums array to 7:
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/02/2010 for the course CIS 200 taught by Professor Staff during the Spring '08 term at Kansas State University.

Page1 / 6

arrays - Arrays Motivation for Arrays Suppose we want to...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online