Introduction to Software Development
GWU Computer Science
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:
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?
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.
char[][] letters;
letters = new char[4][4];
letters[0][0] = 'b'; letters[0][1] = 'a'; // ...
char[][] letters = new char[4][4];
for (int i=1; i<letters.length; i++) { for (int j=0; j<letters.length; j++) { // ... printing/whatever ... } }we have the same upper limit for both rows and colums.
char[][] letters = { {'f','r','a','c','t','u','r','e'}, {'o','u','t','l','i','n'}, {'b','l','o','o','m','i','n','g'}, {}, {'s','e','p','t'} }; for (int i=1; i<letters.length; i++) { for (int j=0; j<letters[i].length; j++) { // ... } }
letters[i]is the whole row and therefore has a length:
letters[i].length
int[][] A = { {1}, {2,2}, {3,3,3}, {4,4,4,4} }; for (int i=0; i<A.length; i++) { for (int j=0; j<A[i].length; j++) { System.out.print (A[i][j]); } System.out.println (); }
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.