Вы находитесь на странице: 1из 47

CSCI 1530

Computer Principles
and Java Programming

Arrays

2013

Outlines
! Introduction to arrays (1-D arrays)
!
!
!
!

Declaring, creating, and initializing arrays


Accessing array elements
Passing arrays to methods
Returning arrays from methods

! 2-D arrays
! Declaring, creating, and initializing 2-D arrays
! 2-D arrays as parameters/arguments and return values

! Array assignment

1 import java.util.*;
2
3 class Example {
4
public static void main(String[] args) {
5
Scanner scanner = new Scanner(System.in);
6
int grade1, grade2, grade3;
7
8
System.out.print("Student 1: ");
9
grade1 = scanner.nextInt();
10
System.out.print("Student 2: ");
11
grade2 = scanner.nextInt();
12
System.out.print("Student 3: ");
13
grade3 = scanner.nextInt();
14
15
System.out.println("Average = " +
16
(grade1 + grade2 + grade3) / 3.0);
17
}
18 }

! The program works if there are only three students.


! What if there are 100 students?

Array to the rescue!


Ordinary
Variable
Like a box for storing
one value

Array
Like a cabinet
containing many
drawers.
Each drawer stores
one value.
We can refer to each
drawer as 1st drawer,
2nd drawer, 3rd drawer,
etc.

Array
! Stores same type of data
! Array size = # of elements in the array
! Array size remains unchanged throughout
program execution
! To refer to an array element
arrayname[ index ]
! Index always starts from 0
! Index to last element is (array size 1)

Array name

grade[0]
grade[1]
grade[2]
grade[3]

.
.
.

.
.
.

grade[96]
grade[97]
grade[98]
grade[99]
Array Index
Storage

Declaring Arrays
! Syntax:
type[] arrayName;

or

type arrayName[];

! type: Data type of each array element


! arrayName: A valid identifier
! E.g.:

int[] grade;
float d[];

// array of integers
// array of floats

! Declaring multiple arrays of the same type in one declaration


int[] arrayA, arrayB;
int arrayA[], arrayB[];

Creating Arrays
! In Java, arrays are objects. So, we have to create them
using new.
! Syntax:
type[] arrayName; // or: type arrayName[];

arrayName = new type[ arraySize ];


! arraySize: Number of elements in the array
! E.g.:
!

grade = new int[12];


d = new float[100];

! Declaring and creating an array at once:


type[] arrayName = new type[ arraySize ];

Creating Arrays
! An array is an object, so it is of reference data
type.
double[] rainfall = new double[12];
rainfall

! Note:

rainfall[2]

! double/int/ is a primitive type.


! But double[]/int[]/ is a reference type

9 10 11

Array Elements
! Each array element holds one value.
// grade is an array of 100 integers
int[] grade = new int[100];
grade[0] = 10;
grade[1] = 3;
System.out.println(grade[0] + " " + grade[1]);

! Index (also called subscript) must be of type int,


short, byte, or char (i.e., integral type, usually int).
! Index can be an expression.
! E.g.: c[i 2] where i is an integer

1 class Example {
2
3
public static void main(String[] args) {
4
5
int n[] = new int[10]; // an array of 10 integers
6
7
// Set all elements of array to 0
8
for ( int i = 0; i < 10; i++ )
9
n[i] = 0;
10
11
System.out.println("Element
Value");
12
13
// output contents of array n in tabular format
14
for ( int j = 0; j < 10; j++ )
15
System.out.printf("%7d%13d\n", j, n[j]);
16
17
}
18 }

Element
0
1
2
3
4
5
6
7
8
9

Value
0
0
0
0
0
0
0
0
0
0

Array Bounds
! Indexes of an array of size N must range from 0 to N-1.
! An array index that is out of this range cause a run-time
error (called array index out of bounds).
int[] c = new int[ 10 ];
int i = 4;
c[ -1 ] = 5;
// Index out of bound
c[ i+6 ] = 0;
// Index out of bound
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Example.main(Example.java:17)

! It is the programmer's responsibility (not the compiler's) to


ensure correct array indexes.

Initializing Arrays In Declaration


! Specify value of each element when array is
declared.
int[] x = { 4, 2, 6, 1, 9 };

! The number of initializers determines the array


size.
! Size of x is automatically determined as 5.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// Initializing an array in array declaration.


class Example {
public static void main(String[] args) {
// use initializer list to initialize array n
int[] n = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
System.out.println("Element

Value");

// output contents of array n in tabular format


for ( int i = 0; i < 10; i++ )
System.out.printf("%7d%13d\n", i, n[i]);
}
}

Element
0
1
2
3
4
5
6
7
8
9

Value
32
27
64
18
95
14
90
70
60
37

Tips: Array Size


! An array is an object. Its public constant attribute
length returns the size of the array.
System.out.print("How many students? ");
int n = scanner.nextInt();
int[] grade = new int[n];

for (int i = 0; i < grade.length; i++) {


System.out.print("Enter student score: ");
grade[i] = scanner.nextInt();
}

! Make program more scalable and reduce the


risk of array out of bounds error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// A program to count the # of 0's, 1's, 2's, and 3's


// among the input values (Version 1).
import java.util.*;
class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] count = new int[4];
int num;
for (int i = 0; i < count.length; i++)
count[i] = 0;
// Set all elements to 0

System.out.println("Enter 10 integers:");
for (int i = 0; i < 10; i++) {
Enter 10 integers:
num = scanner.nextInt();
1 2 3 2 3 1 1 1 1 0
if (num == 0) count[0]++;
No.
Counts
else if (num == 1) count[1]++;
0
1
else if (num == 2) count[2]++;
1
5
else if (num == 3) count[3]++;
2
2
}
3
2
System.out.println("No.
Counts");
for (int i = 0; i < count.length; i++)
System.out.printf("%3d%9d\n", i, count[i]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// A program to count the # of 0's, 1's, 2's, and 3's


// among the input values (Version 2).
import java.util.*;
class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] count = new int[4];
int num;
for (int i = 0; i < count.length; i++)
count[i] = 0;
// Set all elements to 0
System.out.println("Enter 10 integers:");
for (int i = 0; i < 10; i++) {
num = scanner.nextInt();
if (num >= 0 && num < count.length)
count[num]++;
// Increase the count for "num"
}
System.out.println("No.
Counts");
for (int i = 0; i < count.length; i++)
System.out.printf("%3d%9d\n", i, count[i]);
}
}

Arrays and Methods


! Pass an array element to a method
class Foo {
public void print(int x) {
System.out.println(x);
}
}

How about
passing an
entire array
to a
method?

// In class FooExample
int[] arr = new int[10];
Foo f = new Foo();

for (int i = 0; i < arr.length; i++)


f.print( arr[i] );

Arrays as Parameters
State the type (e.g.,
int[]) and parameter
name (e.g., array) as
usual.

Array size can be


accessed through
length.

public void print(int[] array) {


for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
}

Arrays as Arguments
! Just specify array name (without [])
// In class FooExample
Foo f = new Foo();
int[] foo = new int[24];
int[] bar = new int[100];

// Print all elements in foo and bar


f.print( foo );
f.print( bar );

! Can accept an array of the same type of any


size as actual parameter

Arrays and Methods


! Since arrays are of reference types, modifying
an array element in a method "can be seen"
from the caller.
class Foo {
public void doubleElements(int[] num) {
for (int i = 0; i < num.length; i++)
num[i] *= 2;
}
}
// In class FooExample
Foo f = new Foo();
int[] x = {3, 2, 2, 4, 1};
f.doubleElements(x);
System.out.println(x[1]);

3
24 X
24 X
48 X
12
X6 X
num

Arrays as Method Return Values


! A method that returns an array:

Array as
return type

// In class Foo
public double[] getRainfall() {
double[] rainfall = new double[12];

return rainfall;
}

! Calling a method that returns an array


// In class FooExample
Foo f = new Foo();
double[] data;
data = f.getRainfall();

No need to create an
array before calling
the method.

Examples
! The following few slides are some examples
illustrating how we can process the data in an
array. The examples include:
! Computing average of all the numbers in an array
! Finding the largest number in an array
! Locating a data in an array
! Using array elements as indexes to another array

1
2
3
4
5
6
7
8

public double average(int[] num) {


int sum = 0;
for ( int i = 0; i < num.length; i++ )
sum += num[ i ];
return (double)sum / num.length;
}

Example: A method to compute average

1 public int max(int[] num) {


2
int largest;
3
4
largest = num[0];
5
for ( int i = 1; i < num.length; i++ )
6
if (num[i] > largest)
7
largest = num[i];
8
9
return largest;
10 }

Example: A method to find the largest number in an array

1
2
3
4
5
6
7
8
9
10
11
12
13

// This method locates "target" in num.


// Return value:
//
-1 if "target is not found in num.
//
Otherwise location of "target" in num.
public int search(int[] num, int target) {
for ( int i = 0; i < num.length; i++ )
if (num[ i ] == target)
return i;
return -1;
}

! A search method typically returns the location where the


item is found.

1 // Counting the numbers in num


2
3 public void countZeroToNine(int[] num) {
4
int[] count = new int[10];
5
for ( int i = 0; i < count.length; i++
6
count[i] = 0;
// set all elements
7
8
for ( int i = 0; i < num.length; i++ )
9
if ( num[i] >= 0 && num[i] <= 9 )
10
count[ num[ i ] ]++;
11
12
for ( int i = 0; i < count.length; i++
13
System.out.println("# of " + i + ":
14 count[i]);
}

)
to 0

)
" +

Counting numbers in an array


Note: Since inside the if-statement, values in num[i] must be
integers between 0 and 9, we can use these values as indexes
to count directly.

2-D Arrays
!
!
!
!

A table that consists of rows and columns


Conceptually, rectangular in shape
Store values of the same type
Need two indexes to identify each element
Column 0
Row 0
Row 1
Row 2

Column 1

Column 2

Column 3

Declaring and Creating 2-D Arrays


! Declaration:
! type[][] arrayName;
! type arrayName[][];

// variation 1
// variation 2

! Creation:
! arrayName = new type[size1][size2];

! Example:

int[][] a;
a = new int[3][4];

Column 0

Column 1

Column 2

Column 3

Row 0

a[0][0]

a[0][1]

a[0][2]

a[0][3]

Row 1

a[1][0]

a[1][1]

a[1][2]

a[1][3]

Row 2

a[2][0]

a[2][1]

a[2][2]

a[2][3]

1st index to row


2nd index to
column

2-D Array Initialization


! Declaration and initialization

Automatically
determines that a
has 2 rows and 3
columns

// As array of arrays
int[][] a = {{1, 2, 3}, {4, 5, 6}};
a[0]
a[1]

1 2 3
4 5 6

! The size of each row can be different.


// row 0: size 3, row 1: size 2
int[][] b = {{1, 2, 3}, {4, 5}};
b[0]
b[1]

1 2 3
4 5

2-D Array Size of Each Dimension


! Obtaining the size of each dimension of an array
! E.g.:
int[][] array1 = new int[5][9];
System.out.println(array1.length);
System.out.println(array1[0].length);
System.out.println(array1[1].length);

5
9
9

int[][] array2 = {{3, 2, 4}, {5, 9, 7, 1}};


System.out.println(array2.length);
System.out.println(array2[0].length);
System.out.println(array2[1].length);

2
3
4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// arrA, arrB,
int[][] arrA =
1 }};
int[][] arrB =
1 }};
int[][] arrC =

and arrC are 3x3 arrays


{{ 1, 2, 3 }, { 0, -1, 2 }, { 0, 0,
{{ 1, 0, 0 }, { 2, -1, 0 }, { 3, 2,
new int[3][3];

// Adds arrA and arrB, element by element


for (int i = 0; i < arrA.length; i++)
for (int j = 0; j < arrA[i].length; j++)
arrC[i][j] = arrA[i][j] + arrB[i][j];

arrA
1
0
0

2
-1
0

arrB
// Print array arrC
for (int i = 0; i < arrC.length; i++) {
1 0
for (int j = 0; j < arrC[i].length; j++)
2 -1
System.out.printf("%4d", arrC[i][j]);
System.out.println();
3 2
}
Example: adding two 2-D
2
2
3
arrays element by element
2 -2
2
3
2
2

3
2
1
0
0
1

2-D Arrays as Parameters


public void foo(int[][] array) {

! State the array type type[][] and parameter


name as usual. (E.g., int[][] array)
! The size of each dimension of the array can be
obtained using array.length and
array[i].length respectively.
! Parameter can accept any 2-D array of the same
type

2-D Arrays as Parameters


class Foo {
public void foo( int[][] array ) {

}
}
// In class FooExample
Foo f = new Foo();
int[][] a1 = new int[24][4];
int[][] a2 = new int[100][4];
int[][] a3 = new int[10][2];
int[]
a4 = new int[20];
f.foo( a1 );
f.foo( a2 );
f.foo( a3 );

// OK
// OK
// OK

f.foo( a4 );

// Compilation error

class Foo {
public void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
// In class
Foo f = new
int[][] b =
int[][] c =
int[]
d =

FooExample
Foo();
new int[10][4];
new int[2][10];
new int[3];

f.print( d );

// Print all 3 elements in d

f.print( b[1] ); // Print all 4 elements in 2nd row of b


f.print( c[0] ); // Print all 10 elements in 1st row of c
A 2-D array is a 1-D array of 1-D arrays
Note: Each row of a 2-D array is a 1-D array

Returning a 2-D Array


Return type stated as:
type[][]
class Foo {
// A method that returns a 2-D array
public int[][] foo() {
int[][] array = ;

return array;
}
}
// In class FooExample
Foo f = new Foo();
int[][] x;

x = f.foo();

Receiving a reference
of the array from the
method call

Applications of 2-D arrays


! Digital Images (2-D array of pixels)
! Assignment scores of students
! Each row represents a student
! Each column represents the student's scores from
different components

! Game board (Chess, Minesweeper, etc.)


! Spreadsheet
! etc.

Array Assignment
! Two array variables can be assigned from one to
another.
int[] array1 = ;
int[] array2;

array2 = array1;
// ok

! Only a reference of the array is copied.


! Arrays are objects anyway.
array1
array2

Array Assignment
int[] a;
int[] b = { 11, 22, 33, 44, 55 };
int[] c = { 10, 9, 8 };
a = b;

// a and b refers to the same array

System.out.println( a[0] );
System.out.println( a[3] );

// Prints 11
// Prints 44

a[4] = 66;
// b[4] is also changed to 66
System.out.println( b[4] );
// Prints 66
a = c;
// Now, a and c refers to the same array
System.out.println( a[0] );
// Prints 10

int[] array, tempArray;


// Create an array of 5 integers
array = new int[5];
for (int i = 0; i < array.length; i++)
array[i] = i;

// Want to enlarge array to hold 100 integers,


// but keeping its previous contents intact.
// Solution: create another new array (tempArray) and copy
// the contents of old array to the new one, and makes
// array point to the new array
tempArray = new int[100];
for (int i = 0; i < array.length; i++)
tempArray[i] = array[i];
array = tempArray;

An example to illustrate how you can enlarge an array.

To Wrap Up
! Recall our GradeBook example. An object of
class GradeBook is used to store the exam
scores of the students in one course.
! A straightforward choice of attributes of class
GradeBook is:
! Name of the course (a string)
! An array of the students scores (an array of integers)

! Lets enrich our class GradeBook to include


more functionalities.

GradeBook.java
1 class GradeBook {
2
3
private String courseName;
4
private int[] grades;
5
6
public GradeBook(String name, int[] scores) {
7
setCourseName(name);
8
grades = new int[scores.length];
9
for (int i = 0; i < grades.length; i++)
10
if (scores[i] > 100)
11
grades[i] = 100;
12
else
13
grades[i] = scores[i];
14
}
15
16
public void setCourseName(String name) {
17
courseName = name;
18
}
19
20
public String getCourseName() {
21
return courseName;
22
}

GradeBook.java (continue)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

public void displayMessage() {


System.out.println("Welcome to the grade book for "
+ getCourseName() + "!");
}
public void processGrades() {
outputGrades();
System.out.println("Class average is "
+ getAverage());
System.out.println("Lowest grade is " + getMin());
System.out.println("Highest grade is " + getMax());
}
public int getMax() {
int largest = 0;
for (int i = 0; i < grades.length; i++)
if (grades[i] > largest)
largest = grades[i];
return largest;
}

GradeBook.java (continue)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 }

public int getMin() {


int smallest = 100;
for (int i = 0; i < grades.length; i++)
if (grades[i] < smallest)
smallest = grades[i];
return smallest;
}
public double getAverage() {
int sum = 0;
for (int i = 0; i < grades.length; i++)
sum += grades[i];
return (double)sum / grades.length;
}
public void outputGrades() {
System.out.println("The grades are:");
for (int i = 0; i < grades.length; i++)
System.out.printf("Student %3d:%10d\n",
i + 1, grades[i]);
}

1 class GradeBookExample {
2
public static void main(String[] args) {
3
int[] scores = {87, 68, 94, 100, 83,
4
78, 85, 91, 76, 87};
5
6
GradeBook book = new GradeBook("CSC1530", scores);
7
8
book.displayMessage();
9
book.processGrades();
10
}
11 }
GradeBookExample.java

GradeBook.java

GradeBookExample.java

Welcome to the grade book for CSC1530!


The grades are:
Student
1:
87
Student
2:
68
Student
3:
94
Student
4:
100
Student
5:
83
Student
6:
78
Student
7:
85
Student
8:
91
Student
9:
76
Student 10:
87
Class average is 84.9
Lowest grade is 68
Highest grade is 100

Summary
! Understanding the characteristics of 1-D and 2-D arrays
! Knowing how to declare, create, and initialize 1-D and 2D arrays
! Knowing how to process 1-D and 2-D arrays
! Knowing how to pass arrays to methods and return
arrays from methods
! Understand the consequences of array assignment

Вам также может понравиться