Post on 08-Jan-2016
description
7/17/2019 Lec09 Arraysasd
1/47
CSCI 1530Computer Principles
and Java Programming
Arrays
2013
7/17/2019 Lec09 Arraysasd
2/47
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
7/17/2019 Lec09 Arraysasd
3/47
import java.util.*;
classExample {
public static voidmain(String[] args) {
Scanner scanner = newScanner(System.in);
intgrade1, grade2, grade3;
System.out.print("Student 1: ");
grade1 = scanner.nextInt();
System.out.print("Student 2: ");
grade2 = scanner.nextInt();
System.out.print("Student 3: ");
grade3 = scanner.nextInt();
System.out.println("Average = "+
(grade1 + grade2 + grade3) / 3.0);
}
}
! The program works if there are only three students.
! What if there are 100 students?
1
2
3
4
5
67
8
9
10
11
12
1314
15
16
17
18
7/17/2019 Lec09 Arraysasd
4/47
Arrayto the rescue!
Ordinary
VariableLike a box for storing
one value
Array
Like a cabinetcontaining many
drawers.
Each drawer stores
one value.
We can refer to each
drawer as 1stdrawer,2nddrawer, 3rddrawer,
etc.
7/17/2019 Lec09 Arraysasd
5/47
Array
!
Stores same type of data! Array size = # of elements in the array
! Array size remains unchanged throughoutprogram execution
!
To refer to an array element
arrayname[ index ]
! Index always starts from 0
! Index to last element is (array size 1)
grade[0]
grade[1]
grade[2]
grade[3]
grade[96]
grade[97]
grade[98]
grade[99]
Array name
.
..
.
..
Array Index
Storage
7/17/2019 Lec09 Arraysasd
6/47
Declaring Arrays
!
Syntax:
! type: Data type of each array element
!
arrayName: A valid identifier
! E.g.: int[] grade; // array of integers
float d[]; // array of floats
!
Declaring multiple arrays of the same type in one declarationint[] arrayA, arrayB;
int arrayA[], arrayB[];
type[] arrayName; typearrayName[];or
7/17/2019 Lec09 Arraysasd
7/47
Creating Arrays
! In Java, arrays are objects. So, we have to create themusing new.
! Syntax:
! 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; // or: typearrayName[];
arrayName= new type[ arraySize];
type[] arrayName= new type[ arraySize];
7/17/2019 Lec09 Arraysasd
8/47
Creating Arrays
! An array is an object, so it is of reference datatype.
! Note:
!
double/int/!
is a primitive type.
! But double[]/int[]/!is a reference type
double[] rainfall = newdouble[12];
0 1 2 3 4 5 6 7 8 9 10 11
rainfall
rainfall[2]
7/17/2019 Lec09 Arraysasd
9/47
Array Elements
! Each array element holds one value.
! 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 iis an integer
// 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]);
7/17/2019 Lec09 Arraysasd
10/47
classExample {
public static voidmain(String[] args) {
intn[] = new int[10]; // an array of 10 integers
// Set all elements of array to 0
for( inti = 0; i < 10; i++ )
n[i] = 0;
System.out.println("Element Value");
// output contents of array n in tabular format
for( intj = 0; j < 10; j++ )
System.out.printf("%7d%13d\n", j, n[j]);
}
}
1
2
3
4
56
7
8
9
10
11
12
13
14
15
16
17
18
7/17/2019 Lec09 Arraysasd
11/47
Element Value
0 0
1 0
2 0
3 0
4 05 0
6 0
7 0
8 0
9 0
7/17/2019 Lec09 Arraysasd
12/47
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-timeerror (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
! It is the programmer's responsibility(not the compiler's) toensure correct array indexes.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Example.main(Example.java:17)
7/17/2019 Lec09 Arraysasd
13/47
Initializing Arrays In Declaration
! Specify value of each element when array isdeclared.
int[] x = { 4, 2, 6, 1, 9 };
! The number of initializers determines the array
size.
! Size of xis automatically determined as 5.
7/17/2019 Lec09 Arraysasd
14/47
// Initializing an array in array declaration.
class Example {
public static voidmain(String[] args) {
// use initializer list to initialize array nint[] 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( inti = 0; i < 10; i++ )
System.out.printf("%7d%13d\n", i, n[i]);
}
}
1
2
3
4
5
67
8
9
10
11
12
1314
15
16
7/17/2019 Lec09 Arraysasd
15/47
Element Value
0 32
1 27
2 64
3 18
4 955 14
6 90
7 70
8 60
9 37
7/17/2019 Lec09 Arraysasd
16/47
Tips: Array Size
! An array is an object. Its public constant attribute
lengthreturns the size of the array.
! Make program more scalable and reduce the
risk of array out of bounds error.
System.out.print("How many students? ");
intn = scanner.nextInt();
int[] grade = new int[n];
for(inti = 0; i < grade.length; i++) {
System.out.print("Enter student score: ");
grade[i] = scanner.nextInt();
}
7/17/2019 Lec09 Arraysasd
17/47
// A program to count the # of 0's, 1's, 2's, and 3's// among the input values (Version 1).importjava.util.*;
classExample {public static voidmain(String[] args) {
Scanner scanner = newScanner(System.in);int[] count = new int[4];intnum;
for(inti = 0; i < count.length; i++)count[i] = 0; // Set all elements to 0
System.out.println("Enter 10 integers:");for(inti = 0; i < 10; i++) {
num = scanner.nextInt();if(num == 0) count[0]++;else if(num == 1) count[1]++;else if(num == 2) count[2]++;else if(num == 3) count[3]++;
}
System.out.println("No. Counts");for(inti = 0; i < count.length; i++)
System.out.printf("%3d%9d\n", i, count[i]);}
}
12345678910111213
1415161718192021222324252627
Enter 10 integers:
1 2 3 2 3 1 1 1 1 0
No. Counts
0 1
1 5
2 2
3 2
7/17/2019 Lec09 Arraysasd
18/47
// A program to count the # of 0's, 1's, 2's, and 3's
// among the input values (Version 2).
importjava.util.*;
classExample {
public static voidmain(String[] args) {Scanner scanner = newScanner(System.in);
int[] count = new int[4];
intnum;
for(inti = 0; i < count.length; i++)
count[i] = 0; // Set all elements to 0
System.out.println("Enter 10 integers:");
for(inti = 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(inti = 0; i < count.length; i++)
System.out.printf("%3d%9d\n", i, count[i]);
}
}
1
2
3
4
5
67
8
9
10
11
12
1314
15
16
17
18
19
2021
22
23
24
25
7/17/2019 Lec09 Arraysasd
19/47
Arrays and Methods
! Pass an array elementto a method
classFoo {
public voidprint(intx) {
System.out.println(x);
}}
// In class FooExample
int[] arr = new int[10];
Foo f = newFoo();
for(inti = 0; i < arr.length; i++)
f.print( arr[i]);
How about
passing an
entire arrayto a
method?
7/17/2019 Lec09 Arraysasd
20/47
public voidprint(int[] array) {
for(inti = 0; i < array.length; i++)System.out.print(array[i] + " ");
System.out.println();
}
Arrays as Parameters
State the type (e.g.,
int[]) and parameter
name (e.g., array) asusual.
Array size can be
accessed through
length.
7/17/2019 Lec09 Arraysasd
21/47
Arrays as Arguments
! Just specify array name (without [])
! Can accept an array of the same type of any
sizeas actual parameter
// In class FooExample
Foo f = newFoo();
int[] foo = newint[24];
int[] bar = newint[100];
// Print all elements in foo and bar
f.print( foo);
f.print(bar);
7/17/2019 Lec09 Arraysasd
22/47
Arrays and Methods
! Since arrays are of reference types, modifyingan array element in a method "can be seen"
from the caller.
classFoo {public voiddoubleElements(int[] num) {
for(inti = 0; i < num.length; i++)
num[i] *= 2;
}
}
// In class FooExample
Foo f = newFoo();
int[] x = {3, 2, 2, 4, 1};
f.doubleElements(x);
System.out.println(x[1]);
0 1 2 3 4
3 2 2 4 1
num
x
X X X X X6 4 4 8 2
7/17/2019 Lec09 Arraysasd
23/47
Arrays as Method Return Values
! A method that returns an array:
! Calling a method that returns an array
// In class Foo
public double[] getRainfall() {
double[] rainfall = newdouble[12];
returnrainfall;
}
// In class FooExample
Foo f = newFoo();
double[] data;
data = f.getRainfall();
No need to create anarray before calling
the method.
Array as
return type
7/17/2019 Lec09 Arraysasd
24/47
Examples
! The following few slides are some examplesillustrating how we can process the data in anarray. 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
7/17/2019 Lec09 Arraysasd
25/47
public doubleaverage(int[] num) {
intsum = 0;
for( inti = 0; i < num.length; i++ )
sum += num[ i ];
return(double)sum / num.length;
}
1
2
3
4
5
6
7
8
Example: A method to compute average
7/17/2019 Lec09 Arraysasd
26/47
public intmax(int[] num) {
intlargest;
largest = num[0];
for( inti = 1; i < num.length; i++ )
if(num[i] > largest)
largest = num[i];
returnlargest;
}
1
23
4
5
6
78
9
10
Example: A method to find the largest number in an array
7/17/2019 Lec09 Arraysasd
27/47
// 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, inttarget) {
for( inti = 0; i < num.length; i++ )
if(num[ i ] == target)
returni;
return-1;
}
1
2
3
4
5
6
7
8
9
1011
12
13
! A search method typically returns the location where theitem is found.
7/17/2019 Lec09 Arraysasd
28/47
// Counting the numbers in num
public void countZeroToNine(int[] num) {
int[] count = new int[10];
for( inti = 0; i < count.length; i++ )
count[i] = 0; // set all elements to 0
for( inti = 0; i < num.length; i++ )
if ( num[i] >= 0 && num[i]
7/17/2019 Lec09 Arraysasd
29/47
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 Column 1 Column 2 Column 3
Row 0
Row 1
Row 2
7/17/2019 Lec09 Arraysasd
30/47
Declaring and Creating 2-D Arrays
! Declaration:
! type[][] arrayName; // variation 1
! typearrayName[][]; // variation 2
! Creation:
! arrayName= new type[size1][size2];
! Example:
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]
1stindex to row
2ndindex tocolumn
int[][] a;
a = new int[3][4];
7/17/2019 Lec09 Arraysasd
31/47
2-D Array Initialization
! Declaration and initialization// As array of arrays
int[][] a = {{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}};
a[0] 1 2 3
a[1] 4 5 6
Automaticallydetermines that a
has 2 rows and 3columns
b[0] 1 2 3
b[1] 4 5
7/17/2019 Lec09 Arraysasd
32/47
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);
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);
59
9
23
4
7/17/2019 Lec09 Arraysasd
33/47
// arrA, arrB, and arrC are 3x3 arrays
int[][] arrA = {{ 1, 2, 3}, { 0, -1, 2}, { 0, 0,
1}};
int[][] arrB = {{ 1, 0, 0}, { 2, -1, 0}, { 3, 2,
1}};
int[][] arrC = new int[3][3];
// Adds arrA and arrB, element by element
for (inti = 0; i < arrA.length; i++)
for (intj = 0; j < arrA[i].length; j++)
arrC[i][j] = arrA[i][j] + arrB[i][j];
// Print array arrC
for (inti = 0; i < arrC.length; i++) {
for (intj = 0; j < arrC[i].length; j++)
System.out.printf("%4d", arrC[i][j]);
System.out.println();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Example: adding two 2-Darrays element by element
2 2 3
2 -2 2
3 2 2
1 2 3
0 -1 2
0 0 1
1 0 0
2 -1 0
3 2 1
arrA
arrB
7/17/2019 Lec09 Arraysasd
34/47
2-D Arrays as Parameters
! 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.lengthand
array[i].lengthrespectively.
! Parameter can accept any2-D array of the same
type
public voidfoo(int[][]array) {
}
7/17/2019 Lec09 Arraysasd
35/47
2-D Arrays as Parameters
classFoo {public voidfoo( int[][] array) {
}
}
// In class FooExample
Foo f = newFoo();
int[][] a1 = newint[24][4];
int[][] a2 = newint[100][4];
int[][] a3 = newint[10][2];
int[] a4 = newint[20];
f.foo( a1 ); // OK
f.foo( a2 ); // OK
f.foo( a3 ); // OK
f.foo( a4 ); // Compilation error
7/17/2019 Lec09 Arraysasd
36/47
classFoo {
public voidprint(int[] a) {
for(inti = 0; i < a.length; i++)
System.out.println(a[i]);
}}
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
// In class FooExample
Foo f = newFoo();
int[][] b = new int[10][4];
int[][] c = new int[2][10];
int[] d = 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
7/17/2019 Lec09 Arraysasd
37/47
Returning a 2-D Array
classFoo {
// A method that returns a 2-D array
public int[][] foo() {int[][] array = ;
returnarray;
}
}
// In class FooExample
Foo f = newFoo();
int[][] x;
x = f.foo();
Return type stated as:type[][]
Receiving a referenceof the array from the
method call
7/17/2019 Lec09 Arraysasd
38/47
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.
7/17/2019 Lec09 Arraysasd
39/47
Array Assignment
! Two array variables can be assigned from one toanother.
! Only a reference of the array is copied.
!
Arrays are objects anyway.
int[] array1 = ;
int[] array2;
array2 = array1; // ok
0 1 2 !array1
array2
7/17/2019 Lec09 Arraysasd
40/47
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] ); // Prints 11
System.out.println( a[3] ); // 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
7/17/2019 Lec09 Arraysasd
41/47
int[] array, tempArray;
// Create an array of 5 integers
array = newint[5];
for(inti = 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 = newint[100];
for(inti = 0; i < array.length; i++)
tempArray[i] = array[i];
array = tempArray;
An example to illustrate how you can enlarge an array.
7/17/2019 Lec09 Arraysasd
42/47
To Wrap Up!
!
Recall our GradeBookexample. An object ofclass GradeBookis used to store the examscores of the students in one course.
!
A straightforward choice of attributes of classGradeBookis:! Name of the course (a string)
!An array of the students scores (an array of integers)
!
Lets enrich our class GradeBookto includemore functionalities.
7/17/2019 Lec09 Arraysasd
43/47
classGradeBook {
privateString courseName;
privateint[] grades;
publicGradeBook(String name, int[] scores) {
setCourseName(name);
grades = new int[scores.length];
for(inti = 0; i < grades.length; i++)
if(scores[i] > 100)
grades[i] = 100;else
grades[i] = scores[i];
}
public voidsetCourseName(String name) {
courseName = name;
}
publicString getCourseName() {
returncourseName;
}
1
2
3
45
6
7
8
9
10
1112
13
14
15
16
17
1819
20
21
22
GradeBook.java
7/17/2019 Lec09 Arraysasd
44/47
public voiddisplayMessage() {
System.out.println("Welcome to the grade book for "
+ getCourseName() + "!");}
public voidprocessGrades() {
outputGrades();
System.out.println("Class average is "
+ getAverage());System.out.println("Lowest grade is "+ getMin());
System.out.println("Highest grade is "+ getMax());
}
public intgetMax() {
intlargest = 0;
for(inti = 0; i < grades.length; i++)if(grades[i] > largest)
largest = grades[i];
returnlargest;
}
23
24
25
2627
28
29
30
31
32
3334
35
36
37
38
39
4041
42
43
44
GradeBook.java(continue)
7/17/2019 Lec09 Arraysasd
45/47
public intgetMin() {
intsmallest = 100;
for(inti = 0; i < grades.length; i++)
if(grades[i] < smallest)smallest = grades[i];
returnsmallest;
}
public doublegetAverage() {
intsum = 0;
for(inti = 0; i < grades.length; i++)
sum += grades[i];
return(double)sum / grades.length;
}
public voidoutputGrades() {
System.out.println("The grades are:");for(inti = 0; i < grades.length; i++)
System.out.printf("Student %3d:%10d\n",
i + 1, grades[i]);
}
}
45
46
47
48
4950
51
52
53
54
55
56
57
58
59
60
61
6263
64
65
66
67
GradeBook.java(continue)
7/17/2019 Lec09 Arraysasd
46/47
classGradeBookExample {public static voidmain(String[] args) {
int[] scores = {87, 68, 94, 100, 83,78, 85, 91, 76, 87};
GradeBook book = newGradeBook("CSC1530", scores);
book.displayMessage();book.processGrades();
}}
123456
7891011
GradeBookExample.javaWelcome to the grade book for CSC1530!
The grades are:Student 1: 87Student 2: 68Student 3: 94Student 4: 100Student 5: 83Student 6: 78Student 7: 85
Student 8: 91Student 9: 76Student 10: 87Class average is 84.9Lowest grade is 68Highest grade is 100
GradeBookExample.java
GradeBook.java
7/17/2019 Lec09 Arraysasd
47/47
Summary
! Understanding the characteristics of 1-D and 2-D arrays
! Knowing how to declare, create, and initialize 1-D and 2-
D 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