6
Arrays
2
Now go, write it before them in a table, and note it in a book.
— Isaiah 30:8
To go beyond is as wrong as to fall short.
— Confucius
Begin at the beginning,… and go on till you come to the end: then stop.
— Lewis Carroll
3
OBJECTIVES
In this chapter you will learn: What arrays are. To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array. To use the enhanced for statement to iterate through arrays. To pass arrays to methods. To declare and manipulate multidimensional arrays. To write methods that use variable-length argument lists. To read command-line arguments into a program.
4
6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15
Introduction Arrays Declaring and Creating Arrays Examples Using Arrays Case Study: Card Shuffling and Dealing Simulation Enhanced for Statement Passing Arrays to Methods Case Study: Class GradeBook Using an Array to Store Grades Multidimensional Arrays Case Study: Class GradeBook Using a Two-Dimensional Array Variable-Length Argument Lists Using Command-Line Arguments (Optional) GUI and Graphics Case Study: Drawing Arcs (Optional) Software Engineering Case Study: Collaboration Among Objects Wrap-Up
5
6.1 Introduction
• Arrays
– Data structures – Related data items of same type – Remain same size once created
• Fixed-length entries
6
6.2 Arrays
• Array
– Group of variables
• Have same type
– Reference type
7
Fig. 6.1 | A 12-element array.
8
6.2 Arrays (Cont.)
• Index
– Also called subscript – Position number in square brackets – Must be positive integer or integer expression – First element has index zero a = 5; b = 6; c[ a + b ] += 2;
• Adds 2 to c[ 11 ]
9
Common Programming Error 6.1
Using a value of type long as an array index results in a compilation error. An index must be an int value or a value