A program shows how to work with two-dimensional arrays.

// read a 2-D array from the user (the rows may have different
// number of elements)
// Find the average of each row and the total average.
import java.io.*;

public class TwoD {
public static void main(String[] args) throws IOException {
// string for storing a line of input
String line;

// read the number of rows
System.out.print("Please enter the number of rows: ");
int rows = Integer.parseInt(line);

// initialize the array:
double [][] a = new double[rows][];

for(int i = 0; i < rows; ++i) {
// read the number of elements in this row:
System.out.print("How many elements are in row " + i + " ? ");
int elts = Integer.parseInt(line);

// create an array for the row:
a[i] = new double[elts];

for (int j = 0; j < elts; ++j) {
System.out.print("Please enter the element " + j +
" of row  " + i + " : ");
a[i][j] = Double.parseDouble(line);
}
}

// computing the averages:
double sum = 0;
int total_elts = 0;
for (int i = 0; i < a.length; ++i) {
double sum_row = 0;
for (int j = 0; j < a[i].length; ++j) {
sum += a[i][j];
sum_row += a[i][j];
}
System.out.println("The average for row " + i + " is " +
sum_row/a[i].length);
total_elts += a[i].length;
}
System.out.println("The total average is " + sum/total_elts);

}
}

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.