GWU

CS 1111

Introduction to Software Development

GWU Computer Science


Lecture Notes 06: Nested Loops and 2D Arrays


Objectives

By the end of this module, for simple HelloWorld-like programs, you will be able to:




Why are 2D arrays useful in computation?

Nested for-loops



Just like nesting if statements, you can also nest loops! We'll start by writing code that, for a list of integers, produces all the possible pairs in that list.

Let's trace through the code together using the Java Visualizer. You'll notice that even with such a short list, there are many possible pairs -- the study of combinatorics is useful for reasoning about how to make strong passwords that are difficult for an automated system like this one to crack.

Observe:

Activity 1:

Modify your code above so that the inner loop stops when i equals the value of j. How did this change the behavior of the loop?




When things go wrong



As code gets more complex, it gets easier to make mistakes, and harder to find them.

In each of the programs below, try to determine the error without compiling the program. Then, write up the program, compile and see what the compiler says. After that, fix the error.




Two dimensional (2D) arrays



We've been working with grids already this semester, although only "in our minds," that is, we've never stored a 2D grid so far. Since we know how to declare a 1D array already, we can extend this to 2D arrays:

Let's trace through this together in the Java Visualizer and see how this grid is represented in memory.

For dynamic declaration and initializations, we can do something similar than with 1-D arrays.

Activity 3:

Add code to your grid example to print out all of the tiles.



Dealing with rectangles:

Working with grids

We can use a double for loop to walk over the tiles of a grid, by visiting each row, and then each column on each row:
      int[][] grid = {{1, 4, 2, 3},
        {3, 6, 9, 1},
        {9, 1, 2, 4}};
     
      for(int row = 0; row < grid.length; row++){
          System.out.println("start row");
          for(int col = 0; col < grid[row].length; col++){
              System.out.println("\tcurrent tile: " + grid[row][col]);
          }
          System.out.println("end row");
      }
Let's try running this code together in the Java Visualizer.




Meta



We will occasionally step back from the details to comment on how best to learn.

This module was a bit different, a little more challenging than modules 1-3.

What to keep in mind:

Next class:

We'll go through some more in-class exercises on 2D arrays and nested for loops.

Assignments for next lecture:

Take a look at the Homework 4 problems.