Title: Nested loops
1Nested loops
- "Nested" means "one inside the other"
- Let's say we wanted to make a 10x10 times table
- 1 2 3 4 5 6 7 8 9 10
- 2 4 6 8 10 12 14 16 18 20
- 3 6 9 12 15 18 21 24 27 30
- 4 8 12 16 20 24 28 32 36 40
- 5 10 15 20 25 30 35 40 45 50
- 6 12 18 24 30 36 42 48 54 60
- 7 14 21 28 35 42 49 56 63 70
- 8 16 24 32 40 48 56 64 72 80
- 9 18 27 36 45 54 63 72 81 90
- 10 20 30 40 50 60 70 80 90 100
2Nested loops
- Let's start with the first row
- 1 2 3 4 5 6 7 8 9 10
- 2 4 6 8 10 12 14 16 18 20
- 3 6 9 12 15 18 21 24 27 30
- 4 8 12 16 20 24 28 32 36 40
- 5 10 15 20 25 30 35 40 45 50
- 6 12 18 24 30 36 42 48 54 60
- 7 14 21 28 35 42 49 56 63 70
- 8 16 24 32 40 48 56 64 72 80
- 9 18 27 36 45 54 63 72 81 90
- 10 20 30 40 50 60 70 80 90 100
-
- It would be easy enough to write a loop that
makes the numbers 1through 10
3Nested loops
- Let's start with the first row
- 1 2 3 4 5 6 7 8 9 10
- 2 4 6 8 10 12 14 16 18 20 x2
- 3 6 9 12 15 18 21 24 27 30 x3
- 4 8 12 16 20 24 28 32 36 40 x4
- 5 10 15 20 25 30 35 40 45 50 x5
- 6 12 18 24 30 36 42 48 54 60 x6
- 7 14 21 28 35 42 49 56 63 70 x7
- 8 16 24 32 40 48 56 64 72 80 x8
- 9 18 27 36 45 54 63 72 81 90 x9
- 10 20 30 40 50 60 70 80 90 100 x10
-
- We'd put that loop inside another loop, that
"multiplies" it
4Nested loops
- //inside loop counts columns 1 to 10
- 1 2 3 4 5 6 7 8 9 10
- 2 4 6 8 10 12 14 16 18 20 x2
- 3 6 9 12 15 18 21 24 27 30 x3
- 4 8 12 16 20 24 28 32 36 40 x4
- 5 10 15 20 25 30 35 40 45 50 x5
- 6 12 18 24 30 36 42 48 54 60 x6
- 7 14 21 28 35 42 49 56 63 70 x7
- 8 16 24 32 40 48 56 64 72 80 x8
- 9 18 27 36 45 54 63 72 81 90 x9
- 10 20 30 40 50 60 70 80 90 100 x10
5Nested loops
- //outside loop counts rows 1 to 10
- //(inside loop column)outside row
- 1 2 3 4 5 6 7 8 9 10
- 2 4 6 8 10 12 14 16 18 20 x2
- 3 6 9 12 15 18 21 24 27 30 x3
- 4 8 12 16 20 24 28 32 36 40 x4
- 5 10 15 20 25 30 35 40 45 50 x5
- 6 12 18 24 30 36 42 48 54 60 x6
- 7 14 21 28 35 42 49 56 63 70 x7
- 8 16 24 32 40 48 56 64 72 80 x8
- 9 18 27 36 45 54 63 72 81 90 x9
- 10 20 30 40 50 60 70 80 90 100 x10
6In Class
- Write an application that generates a 10x10 times
table using nested loops and displays it using
System.out.print() - Hints
- Start RealJ, choose New Project Application
Project - Delete the two import statements, extends Frame
and the class constructor - Use "\t" to space numbers
- Use an empty System.out.println() to end the line
7In Class
- Next, Modify your application so that it produces
the following output - (1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (1,7) (1,8) (1
,9) (1,10) - (2,1) (2,2) (2,3) (2,4) (2,5) (2,6) (2,7) (2,8) (2
,9) (2,10) - (3,1) (3,2) (3,3) (3,4) (3,5) (3,6) (3,7) (3,8) (3
,9) (3,10) - (4,1) (4,2) (4,3) (4,4) (4,5) (4,6) (4,7) (4,8) (4
,9) (4,10) - (5,1) (5,2) (5,3) (5,4) (5,5) (5,6) (5,7) (5,8) (5
,9) (5,10) - (6,1) (6,2) (6,3) (6,4) (6,5) (6,6) (6,7) (6,8) (6
,9) (6,10) - (7,1) (7,2) (7,3) (7,4) (7,5) (7,6) (7,7) (7,8) (7
,9) (7,10) - (8,1) (8,2) (8,3) (8,4) (8,5) (8,6) (8,7) (8,8) (8
,9) (8,10) - (9,1) (9,2) (9,3) (9,4) (9,5) (9,6) (9,7) (9,8) (9
,9) (9,10) - (10,1) (10,2) (10,3) (10,4) (10,5) (10,6) (10,7) (
10,8) (10,9) (10,10) - Which loop gives the row? Which loop gives the
column? Change your variable names so that they
match.
82 dimensional arrays
- Can be thought of as a grid with rows and
columns
column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
92 dimensional arrays
- int naNums -3, -1, 5,
- 7, 12, 13
- /In this form, Java automatically sizes the
array to 2 rows and 3 columns - Note rows first, then columns /
- System.out.println(naNums12)
- //displays 13
- System.out.println(naNums21)
- //Out of bounds exception!
column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
102 dimensional arrays
- int naNums
- /In Java, arrays are objects. If we declare and
initialize the array seperately, we need to use
"new" / - naNums new int23
112 dimensional arrays
- int naNums
- naNums new int23
- Typically, nested loops are used to initialize a
2d array. The outside loop controls the row, and
the inside the column - for(int nRow 0 nRow lt 2 nRow)
- for(int nCol 0 nCol lt 3 nCol)
- naNumsnRownCol nCol(3nRow)
column 0 1 2
0
1
2
row 0
3
4
5
row 1
12A one dimensional array of buttons
- import java.awt.
- import java.awt.event.
- import java.applet.
- public class Buttons extends Applet implements
ActionListener -
- Button buttonArray
- int nRows 3
- int nColumns 4
- int nTotalButtons nRows nColumns
- public void init()
-
- //declare a grid layout with no space
between buttons - setLayout(new GridLayout(nRows, nColumns,
0, 0)) -
- //declare a new array of buttons
- buttonArray new ButtonnTotalButtons
-
- //initialize each of the buttons in the
array
13A one dimensional array of buttons
- import java.awt.
- import java.awt.event.
- import java.applet.
- public class Buttons extends Applet
- implements ActionListener
-
- Button buttonArray
- int nRows 3
- int nColumns 4
- int nTotalButtons nRows nColumns
- public void init()
-
- //declare a grid layout with no space
between buttons - setLayout(new GridLayout(nRows, nColumns,
0, 0)) -
- //declare a new array of buttons
- buttonArray new ButtonnTotalButtons
-
14A one dimensional array of buttons
- import java.awt.
- import java.awt.event.
- import java.applet.
- public class Buttons extends Applet
- implements ActionListener
-
- Button buttonArray
- int nRows 3
- int nColumns 4
- int nTotalButtons nRows nColumns
- public void init()
-
- //grid layout with no space between buttons
- setLayout(new GridLayout(nRows,nColumns,0,0))
- //declare a new array of buttons
- buttonArray new ButtonnTotalButtons
- //initialize each of the buttons in the array
- //with an empty label
15A one dimensional array of buttons
- import java.awt.
- import java.awt.event.
- import java.applet.
- public class Buttons extends Applet
- implements ActionListener
-
- Button buttonArray
- int nRows 3
- int nColumns 4
- int nTotalButtons nRows nColumns
- public void init()
-
- //grid layout with no space between buttons
- setLayout(new GridLayout(nRows,nColumns,0,0))
- //declare a new array of buttons
- buttonArray new ButtonnTotalButtons
- //initialize each of the buttons in the array
- //with an empty label
16A one dimensional array of buttons
- public void actionPerformed(ActionEvent e)
-
- //get number of button from getActionCommand
- //convert it to int and store in nButtonNumber
- int nButtonNumber
- Integer.parseInt(e.getActionCommand())
-
- //display button Number at bottom of screen
- showStatus("Button number " nButtonNumber)
-
- //change background of buttons
if(buttonArraynButtonNumber.getBackground() - ! Color.red)
- buttonArraynButtonNumber.
- setBackground(Color.red)
- else
- buttonArraynButtonNumber.
- setBackground(Color.blue)
-
-
17How would we modify the example for minesweeper?
- When a button is pressed, we need to know two
numbers the row and column - We also need to know if the button is hiding a
mine
18extending the Button class
- class Cell extends Button
-
- private boolean bIsBomb
- private int myRow, myCol
- . . .
19extending the Button class
- class Cell extends Button
-
- private boolean bIsBomb
- private int myRow, myCol
- public Cell(??)
-
- ??
-
20extending the Button class
- class Cell extends Button
-
- private boolean bIsBomb
- private int myRow, myCol
- public Cell(??)
-
- ??
-
- public int getRow()return myRow
21In actionPerformed
- To find out the row (and column) of the button
that was pressed - public void actionPerformed(ActionEvent e)
-
- int nRow ((Cell)e.getSource()).getRow()
22In actionPerformed
- To find out the row (and column) of the button
that was pressed - //Get the object that generated the event
- e.getSource()
- //Cast it as a Cell
- (Cell)e.getSource()
- //Then ask it what row it came from
- ((Cell)e.getSource()).getRow()
23Recursion Reverse Digits
- public class ReverseDigits
-
- public static void main(String args)
-
- reverse(321)
-
- public static void reverse(int nNum)
-
- ???
-
24Recursion Reverse Digits
- public class ReverseDigits
-
- public static void main(String args)
-
- reverse(321)
-
- public static void reverse(int nNum)
-
- System.out.print(nNum10)
- ??
-
25Recursion Reverse Digits
- public class ReverseDigits
-
- public static void main(String args)
-
- reverse(321)
-
- public static void reverse(int nNum)
-
- System.out.print(nNum10)
- if(nNumgt10)
- ??
-
26Recursion Reverse Digits
- public class ReverseDigits
-
- public static void main(String args)
-
- reverse(321)
-
- public static void reverse(int nNum)
-
- System.out.print(nNum10)
- if(nNumgt10)
- reverse(nNum/10)
-
27Recursion
- What will this recursive program display?
- public class RecursiveDemo
-
- static String saWords
- "one","two","three","."
- public static void main(String args)
-
- stackWords(0)
-
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
28Recursion
- When we run this program, the output is
backwards - end
- .
- three
- two
- one
- Why? Each time the recursive call to stackWords()
is made, execution goes back to the start of a
new method call. - The computer must "remember" to complete all the
method calls
29Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Because we can't finish the call until make
another, the calls "stack up" - Call saWordsnPosition
- stackWords(0) one
30Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Call saWordsnPosition
- stackWords(1) two
- stackWords(0) one
31Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Call saWordsnPosition
- stackWords(2) three
- stackWords(1) two
- stackWords(0) one
32Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Once we get to the period, we stop making calls,
and the computer can finish the calls on the
stack - This is called the Base Case
- Call saWordsnPosition
- stackWords(3) .
- stackWords(2) three
- stackWords(1) two
- stackWords(0) one
- Output
- end
- .
33Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Once we get to the period, we stop making calls,
and the computer can finish the calls on the
stack - This is called the Base Case
- Call saWordsnPosition
- stackWords(2) three
- stackWords(1) two
- stackWords(0) one
- Output
- end
- .
- three
34Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Once we get to the period, we stop making calls,
and the computer can finish the calls on the
stack - This is called the Base Case
- Call saWordsnPosition
- stackWords(1) two
- stackWords(0) one
- Output
- end
- .
- three
- two
35Recursion
- public static void stackWords(int nPosition)
-
- if(saWordsnPosition.equals("."))
- System.out.println("end")
- else
- stackWords(nPosition 1)
- System.out.println(saWordsnPosition)
-
- Once we get to the period, we stop making calls,
and the computer can finish the calls on the
stack - This is called the Base Case
- Call saWordsnPosition
- stackWords(0) one
- Output
- end
- .
- three
- two
- one
36Problem
- Write a simple application that finds the
factorial of an integer - 3! 3 2 1
- Hint You will need a method like
- public static int factorial(int nInt)
37Recursion in 2d arrays
- Problem Write a "Remove Blob" method. A Blob
is a collection of one or more dark adjacent
cells.
- There are 4 Blobs on the right
- Clicking on any dark cell should remove the
entire Blob
38A BlobCell class
- class BlobCell extends Button
-
- private int myRow, myCol
- public BlobCell
- (int nR, int nC, String sText)
-
- super(sText)
- myRow nR
- myCol nC
-
- public int getRow()return myRow
- public int getCol()return myCol
39The "Applet" class
- public class RemoveBlobDemo extends Applet
- implements ActionListener
-
- BlobCell buttonArray
- final static int nROWS 9
- final static int nCOLUMNS 9
- static Random randGen new Random()
- // init() not shown
- public void actionPerformed(ActionEvent e)
-
- int nRow
- ((BlobCell)e.getSource()).getRow()
- int nCol
- ((BlobCell)e.getSource()).getCol()
- removeBlob(nRow,nCol)
-
-
40The removeBlob method
- public class RemoveBlobDemo extends Applet
- implements ActionListener
-
- . . .
- public void removeBlob(int nRow,int nCol)
-
- if(buttonArraynRownCol.getBackground()
- .equals(Color.black))
-
- buttonArraynRownCol.
- setBackground(Color.white)
- . . . .
-
41The removeBlob method
- public class RemoveBlobDemo extends Applet
- implements ActionListener
-
- . . .
- public void removeBlob(int nRow,int nCol)
-
- if(buttonArraynRownCol.getBackground()
- .equals(Color.black))
-
- buttonArraynRownCol.
- setBackground(Color.white)
- //Check 8 neighbors
- if(nRow gt 0 nCol gt 0 )
- removeBlob(nRow-1,nCol-1)
-
42Finishing MBSCS Chapter 2
- page 26
- What will the following code do?
- Location loc1 new Location(7,3)
- Location loc2 new Location(7,4)
- Direction dir1 env.getDirection(loc1,loc2)
- Direction dir2 dir1.toRight(90)
- Direction dir3 dir2.reverse()
- Location loc3 env.getNeighbor(loc1,dir3)
- Location loc4 env.getNeighbor(new
Location(5,2), dir1) - We can write a simple program (a driver) to find
out
43Finishing MBSCS Chapter 2
- page 26
- public class WhatOutput
-
- public static void main(String args)
-
- BoundedEnv env new BoundedEnv(10, 10)
- Location loc1 new Location(7,3)
- Location loc2 new Location(7,4)
- Direction dir1 env.getDirection(loc1,lo
c2) - Direction dir2 dir1.toRight(90)
- Direction dir3 dir2.reverse()
- Location loc3 env.getNeighbor(loc1,dir3
) - Location loc4 env.getNeighbor(new
-
Location(5,2), dir1) - System.out.println(loc1)
- //and so on . . .
-
44Finishing MBSCS Chapter 2
- page 33
- Both the Fish and Environment classes keep track
of where a fish is. If they agree it called
consistent, if they disagree it is called
inconsistent. - If you were to remove a fish from the
environment, the fish would still think it was
still at it's old location. The environment
wouldn't.
45Finishing MBSCS Chapter 2
- page 37
- Here's a driver that finds out how many neighbors
(0,0) has. Why is it only two? - public class WhatOutput
-
- public static void main(String args)
-
- BoundedEnv env new BoundedEnv(10, 10)
- Location loc1 new Location(0,0)
- System.out.println(env.neighborsOf(loc1))
-
-
- / Sample Output
- (0, 1), (1, 0)
- Exit code 0
- No Errors /
46Finishing MBSCS Chapter 2
- page 40
- Modify the Fish class by adding a changeColor
method - public class Fish implements Locatable
-
- public void changeColor(Color newColor)
-
- myColor newColor
-
- //and so on. . .
47Finishing MBSCS Chapter 2
- pages 42-43 are confusing
- On page 42, there are 10 "bulleted" statements.
Those are the "black box test cases" - page 43, question 2 "Which black box test cases
cover the last three cases for the loop. . ." - means which of the bulleted statements will test
what happens for "multiple neighboring
locations"? The 3rd bullet, a single fish, is
one correct answer
48Finishing MBSCS Chapter 2
- pages 45 For 2, you could write code like
49Practice Quiz Questions
- Which of the following calls to this method
create infinite recursion? - public void mystery(int nNum1, int nNum2)
-
- if(nNum1 ! nNum2)
- mystery(nNum1 1, nNum2 - 1)
-
- mystery(2,3)
- mystery(3,3)
- mystery(2,4)
- none of the above
50Practice Quiz Questions
- Complete the following method so that clicking on
a black button changes it's background to white
AND the background of all the adjacent buttons to
the right
public void removeRowRight(int nRow,int nCol)
if(buttonArraynRownCol.getBackground(
).equals(Color.black))
buttonArraynRownCol.setBackground(Color.white)
if(__________________________)
_________________________________________
51- A class of 30 students rated their cs teacher on
a scale of 1 to 10. The response array is a 30
element integer array of the student reponses.
An 11 element array will count the number of
occurrences of each response. For example
freq6 will count the number of students who
responded 6. The quantity freq0 will not be
used. Here is a program that counts the
students' responses and outputs the results - public class StudentEvaluations
-
- public static void main(String args)
-
- int responses 6,6,7,8,10,1,5,4,6,7,5,4,
3,4 - ,4,9,8,6,7,10,6,7,8,8,9,6,7,8,9
,2 - int freq new int11
- for(int i0iltresponses.lengthi)
- freqresponsesI
-
-
- Suppose the last entry in the initializer list
for the responses array was incorrectly typed as
12 instead of 2. What would be the result of
running the program? - A rating of 12 would be listed with a frequency
of 1 - A rating of 1 would be liste with a frequency of
12 - An ArrayIndexOutOfBoundsException would be thrown
- A StringIndexOutOfBoundsException would be thrown
- A NullPointerException would be thrown