University of Toronto - Fall 2000
Department of Computer Science

Week 10 - 2D Array Example

MatrixTriangle.java

// MatrixTriangle:  This class shows how to print the lower triangle
//                  of a 2D square matrix.
//                  It's a complete solution for the example discussed
//                  in lecture.

import java.io.*;
public class MatrixTriangle {
	public static void main (String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader
						(System.in));

		// User enters one dimension of the 2D array.
		System.out.print ("Enter array size: ");
		int size = Integer.parseInt(in.readLine());
		System.out.println ("   Array is " + size + "x" + size);

		// Create a 2D array.
		int[][] a = new int[size][size];

		// User enters values, which are put into the array.
		System.out.print ("Enter " + size*size + " integer values");
		System.out.println (" (one per line): ");
		for (int r = 0; r < a.length; r++) {
			for (int c = 0; c < a[0].length; c++) {
				a[r][c] = Integer.parseInt(in.readLine());
			}
		}

		// Print original array.
		System.out.println ("Original array:");
		for (int r = 0; r < a.length; r++) {
			for (int c = 0; c < a[0].length; c++) {
				System.out.print (a[r][c] + " ");
			}
			System.out.println();
		}

		// Print only the lower triangle, starting with element (0,0),
		// continuing down column 0, across the last row, and up the
		// diagonal.

		// Print down column 0
		for (int r = 0; r < a.length; r++) {
			System.out.println (a[r][0]);
		}

		// Print across the last row
		for (int c = 1; c < a.length; c++) {
			System.out.println (a[a.length-1][c]);
		}

		// Print up the diagonal
		for (int r = a.length-2; r > 0; r--) {
			System.out.println (a[r][r]);
		}
	}
}

Output for MatrixTriangle.java

Enter array size: 4
   Array is 4x4
Enter 16 integer values (one per line):
3
5
2
6
7
9
8
3
1
6
7
3
4
2
9
8
Original array:
3 5 2 6
7 9 8 3
1 6 7 3
4 2 9 8
3
7
1
4
2
9
8
7
9