Beruflich Dokumente
Kultur Dokumente
Java Programming:
From Problem Analysis to Program Design,
Second Edition
Learning Objectives
Revise about arrays.
Explore how to declare and manipulate data into
arrays.
Become familiar with the restrictions on array
processing.
Discover how to pass an array as a parameter to a
method.
Discover how to manipulate data in a two-dimensional
array.
Learn about multidimensional arrays.
These statements store 5, 10, 15, and 20, respectively, in the first four
components of numList.
numList[0] = 5;
numList[1] = 10;
numList[2] = 15;
numList[3] = 20;
You can store the number of filled elements, that is, the actual number of
elements, in the array in a variable, say noOfElement. It is a common
practice for a program to keep track of the number of filled elements in an
array.
if (sales.length != 0)
average = sum / sales.length;
else
average = 0.0;
maxIndex = 0;
largestSale = sales[maxIndex];
Print
for (row = 0; row < matrix.length; row++)
{
for (col = 0; col < matrix[row].length;
col++)
System.out.printf("%7d", matrix[row][col]);
System.out.println();
}
Java Programming: From Problem Analysis to Program Design, Second Edition 32
Two-Dimensional Arrays: Processing
Input
for (row = 0; row < matrix.length; row++)
for (col = 0; col < matrix[row].length;
col++)
matrix[row][col] = console.nextInt();
Sum by Row
for (row = 0; row < matrix.length; row++)
{
sum = 0;
for (col = 0; col < matrix[row].length;
col++)
sum = sum + matrix[row][col];
System.out.println("Sum of row " + (row + 1)
+ " = "+ sum);
}
Java Programming: From Problem Analysis to Program Design, Second Edition 33
Two-Dimensional Arrays: Processing
Sum by Column
for (col = 0; col < matrix[0].length; col++)
{
sum = 0;
for (row = 0; row < matrix.length; row++)
sum = sum + matrix[row][col];
System.out.println("Sum of column " + (col + 1)
+ " = " + sum);
}