GWU

CS 1111

Introduction to Software Development

GWU Computer Science


Lecture Notes 14: Intro to 2-D Arrays


Objectives

By the end of this module, you will:




Before Starting

If you do not have your Codio course ready, use any text editor or simple IDE. Some possibilities are:




Catching Up

Before we move forward, let's catch up (complete any remaining work from the previous module)
In this case, make sure we've got:

  1. One-Dimensional Arrays... Declaring, Initializing, and Accessing!




Objectives

By the end of this module, you will:




Two dimensional (2D) arrays



Let's start with a an example of a 1D array of Strings, each of which has characters at a different index. This is NOT a proper 2D array, but it can be worked as such.

Let's use word squares as an example:

Activity 1: In MyWordSquare.java use charAt() to solve this problem. That is, write a method called isWordSquare(String[] words) that returns true or false, depending on whether the words form a valid word square. Then, in main() write the above two lines of code to test.



Now With an actual 2D Array of Chars

Let's print out the word square:
  for (int i=0; i<letters.length; i++) {
      for (int j=0; j<letters.length; j++) {
          // Use print so that the row appears on one line:
          System.out.print (letters[i][j]); 
      }
      // Go to next line for next row:
      System.out.println ();
  }
     

We could choose to print the elements of the main diagonal: top-left(TL) to bottom-right(BR) as in:

  for (int i=0; i<letters.length; i++) {
      System.out.print (letters[i][i]);
  }
  System.out.println ();
     
Activity 2: In MyWordSquare2.java print the whole square, and both diagonals (TL-to-BR and BL-to-TR).

Dealing with rectangles: Activity 3: In PoorPrintExample.java print this array:
  int[][] A = {
      {1, 2, -3, 4},
      {1, 22, 333, 4444},
      {4, -5, 66, 777}
    };
     
In the above example, you saw the the result was an unappealing jagged print.

We will instead use printf to neatly print a 2D array:

  for (int i=0; i<A.length; i++) {
      for (int j=0; j<A[i].length; j++) {
          System.out.printf (" %5d", A[i][j]);
      }
      System.out.println ();
  }
     

Activity 4: In NicePrintExample.java print this array neatly:
  double[][] A = {
      {1.1, 2.222, -3.3, 4.4444},
      {1.0, 2.2, 33.3, 444.4},
      {0.4, -5.0, 0.66, 0.0777}
  };