Nested Loops - PowerPoint PPT Presentation

1 / 55
About This Presentation
Title:

Nested Loops

Description:

Nested Loops – PowerPoint PPT presentation

Number of Views:215
Avg rating:3.0/5.0
Slides: 56
Provided by: jeffreysro
Category:

less

Transcript and Presenter's Notes

Title: Nested Loops


1
Introduction to Computer Science
Unit 10
  • Nested Loops
  • Two Dimensional Arrays

2
Arrays and Loops
  • Before, I said that there is a strong connection
    between loops (action) and arrays (data)
  • Today, we look at two-dimensional arrays
  • Two-dimensional arrays are strongly connected to
    nested loops (loops within loops)

3
Remember the Wind-Chill Factor?

temperature wind 4 mph,
91.4 - (10.45 6.69Öwind - (0.447 x wind) )
x (91.4 - temperature) / 22.0 4 mph ltwind
45 mph,
Wind-chillindex
(1.6 x temperature) - 55.0 wind gt 45 mph.
4
In Java, that was
if (windSpeed lt 4) windChillIndex
temperatureelse if (windSpeed lt
45) windChillIndex 91.4 - ((10.45
(6.69 Math.sqrt(windSpeed)) - (0.447
windSpeed) ) ( (91.4 - temperature) /
22.0))else windChillIndex (1.6
temperature) - 55.0
5
We want to print the following wind-chill table
Table of Wind-Chill Indicesdegrees
F 50 40 30 20 10 0 -10 0 mph 50 40 30 20 10 0 -1
05 mph 48 37 27 16 6 -5 -1510
mph 40 28 16 3 -9 -21 -3415 mph 36 22 9 -5 -18
-32 -4520 mph 32 18 4 -11 -25 -39 -5325
mph 30 15 0 -15 -30 -45 -5930
mph 28 13 -3 -18 -33 -49 -6435
mph 27 11 -5 -20 -36 -51 -67
6
Seeing the Structure
  • There are an awful lot of numbers in that table
  • The key to understanding how to generate the
    table is to understand the structure, and
    translate it into loops
  • We use two loops, nested one for the rows, and
    one for the columns

7
The Outer Loop, for Rows
pre-loop preparation
Table of Wind-Chill Indicesdegrees
F 50 40 30 20 10 0 -10 0 mph 50 40 30 20 10 0 -1
05 mph 48 37 27 16 6 -5 -1510
mph 40 28 16 3 -9 -21 -3415 mph 36 22 9 -5 -18
-32 -4520 mph 32 18 4 -11 -25 -39 -5325
mph 30 15 0 -15 -30 -45 -5930
mph 28 13 -3 -18 -33 -49 -6435
mph 27 11 -5 -20 -36 -51 -67
Loop
1
2
3
4
5
6
7
8
8
The Outer Loops Structure
print the titleprint the heading line of the
tablefor (int i 0 i lt 7 i) print
wind-chill indices for 5 i mph move to next
output line
pre-loop preparation
Table of Wind-Chill Indicesdegrees
F 50 40 30 20 10 0 -10 0 mph 50 40 30 20 10 0 -1
05 mph 48 37 27 16 6 -5 -1510
mph 40 28 16 3 -9 -21 -34
Loop
1
2
3

9
The Inner Loop, for Columns
0 mph 50 40 30 20 10 0 -10
pre-loop preparation
1
2
3
4
5
6
7
Loop
10
The Inner Loop, for Columns
print label 5 i mphfor (int j 5 j gt -1
j--) print the rounded wind-chill index of
5 i mph, 10 j degrees Fahrenheit
0 mph 50 40 30 20 10 0 -10
pre-loop preparation
1
2
3
4
5
6
7
Loop
11
Nesting them together, we have
print the titleprint the heading line of the
tablefor (int i 0 i lt 7 i) print
label 5 i mph for (int j 5 j gt -1 j--)
print the rounded wind-chill index of 5 i
mph, 10 j degrees Fahrenheit move to next
output line
12
Printing the Header Line Also Involves a Loop
print degrees F for (int j 5 j gt -1
j--) print the column heading of 10 j
degrees Fahrenheit move to next output line
pre-loop preparation
degrees F 50 40 30 20 10 0 -10
1
2
3
4
5
6
7
Loop
13
In Java, these Loops Are
System.out.println(Table of Wind-Chill
Indices)System.out.print(degrees F)for
(int j 5 j gt -1 j--) System.out.print(\t
(10j))System.out.println( )System.out.print
ln( )for (int i 0 i lt 7 i)
System.out.print((5i) mph) for (int j
5 j gt -1 j--) System.out.print(\t
(int) Math.round(
windChillIndex(10j, 5i))) System.out.println(
)



14
Inner Loop of Nested Loops Related to Outer Loop
  • Sometimes the limits of the inner loop depend on
    the index value of the outer loop
  • The outer loop (for example) might have an index
    value of 1, then 2, then 3, then 4while the
    inner loop goes from 1 to 1 1 to 2 1 to
    3 1 to 4depending on the outer loop index value

15
How Do We Print the Following?


16
Like This


for (int i 1 ilt10 i) for (int j 1 j
lt i j) System.out.print() System.out
.println( )
17
The Values of the Indices
for (int i 1 ilt10 i) for (int j 1 j
lt i j) System.out.print() System.out
.println( )


i j 1 1 2 1 2 3 1 2 3
18
Seeing the Pattern
  • The hard thing is not to understand how it was
    done
  • The hard thing is to see the pattern in the
    output, and figure out how to build the loop
    yourselves to get the right effect.

19
How Do We Print the Following?

20
Like This

for (int i 1 ilt9 i) for (int j 0 j
lt Math.abs(i - 5) j)
System.out.print() System.out.println( )
21
The Values of the Indices
for (int i 1 ilt9 i) for (int j 0 j
lt Math.abs(i - 5) j) System.out.print(
) System.out.println( )

i j i - 5 1 0, 1, 2, 3, 4 1 - 5
-4 2 0, 1, 2, 3 2 - 5 -3 3 0, 1, 2 3 -
5 -2 4 0, 1 4 - 5 -1 5 0 5 - 5
0 6 0, 1 6 - 5 1 7 0, 1, 2 7 - 5
2
22
How About the Following?

23
One Pattern Inside Another

24
One Pattern Inside Another

for (int i 1 ilt10 i) if ( (i 2) 0
) // i is even for (int j 1 j lt i/2
j) System.out.print() else // i
is odd for (int j 1 j lt 5 - (i/2)
j) System.out.print()
System.out.println( )
25
The Values of the Indices
i j 1 1, 2, 3, 4, 5 2 1 3 1, 2, 3,
4 4 1, 2 5 1, 2, 3 6 1, 2, 3 7 1, 2 8
1, 2, 3, 4 9 1 10 1, 2, 3, 4, 5

for (int i 1 ilt10 i) if ( (i 2) 0
) // i is even for (int j 1 j lt i/2
j) System.out.print()
else // i is odd for (int j 1 j lt 5 -
(i/2) j) System.out.print()
System.out.println( )
26
Simple Chanukia
  • Put candles in from right to left (print 8 - i
    spaces on left)
  • Simple Outer loop from 1 to 8 Inner loop
    of 8 - i spaces Inner loop of i asterisks
    System.out.println( )


27
Simple Chanukia Java Code
for (int i 1 ilt8 i) for (int j 1 j
lt 8 - i j) System.out.print( ) for
(int j 1 j lt i j) System.out.print(
) System.out.println( )


28
Complex Chanukia
  • --------
    --------
    --------
  • Put candles in from right to left (print 8 - i
    spaces on left)
  • Light candles from left to right
  • An unlit candle is
  • A lit candle is
  • Print - 8 times to separate days

etc.
29
Analyze the Loops I
  • --------
    --------
    --------

i 1

The outer loop handles the 8 days
i 2

i 3
etc.
30
Analyze the Loops II
  • --------
    --------
    --------

2
Within each day, there are i 1 lines, followed
by a separating dash. So there will be an inner
loop to handle the i 1 lines within each day.
i 1

3
i 2

i 3
4
etc.
31
Analyze the Loops III

j 0j 1
  • --------
    --------
    --------

i 1
Within each line, we print 8 - i spaces, followed
by a certain number of times (maybe zero),
followed by a certain number of times (maybe
zero) in terms of i and j, what are these
numbers?

j 0j 1j 2
i 2

j 0j 1j 2j 3
i 3
etc.
32
Number of s per line

j 0j 1
  • --------
    --------
    --------

0101201230
i 1

j 0j 1j 2
i 2
is printed exactly j times on each line!

j 0j 1j 2j 3
i 3
etc.
33
Number of s per line

j 0j 1
  • --------
    --------
    --------

1021032104
i 1

j 0j 1j 2
i 2
is printed exactly i - j times on each line!

j 0j 1j 2j 3
i 3
etc.
34
Putting it All Together The Java Code for
Complex Chanukia
  • --------
    --------
    --------

for (int i 1 ilt8 i) for (int j 0 j
lt i j) for (int k 1 k lt 8 - i
k) System.out.print( ) for
(int m 1 m lt j m) System.out.print(
) for (int n 1 n lt i - j n)
System.out.print()
System.out.println( ) System.out.println(---
----- )
etc.
35
Putting it All Together The Java Code for
Complex Chanukia
for (int i 1 ilt8 i) // handle the 8
days for (int j 0 j lt i j) // lines
within a day for (int k 1 k lt 8 - i
k) // spaces per line System.out.print(
) for (int m 1 m lt j m) //
per line System.out.print()
for (int n 1 n lt i - j n) // per
line System.out.print()
System.out.println( ) // end the
line System.out.println(-------- ) //
day separator
36
Two Dimensional Arrays
  • Now that weve gotten some experience with nested
    loops, lets look at two-dimensional arrays in
    Java
  • Regular loops are tightly connected with
    one-dimensional arrays
  • Nested loops are tightly connected with
    multi-dimensional arrays

37
A two dimensional array holds a table of similar
information
energyTable
0
1
2
3
4
5
6
0
18.9
19.4
34.2
2.9
5.7
0.3
11.2
19.1
19.3
33.6
3.0
6.2
0.2
12.1
1
2
18.8
19.6
32.9
3.1
6.6
0.2
11.9
38
A two dimensional array holds a table of
information (of the same type)
double energyTable new double37
0
1
2
3
4
5
6
0
18.9
19.4
34.2
2.9
5.7
0.3
11.2
19.1
19.3
33.6
3.0
6.2
0.2
12.1
1
2
18.8
19.6
32.9
3.1
6.6
0.2
11.9
39
Row - Column Indices
energyTable21
energyTable05
0
1
2
3
4
5
6
0
0.3
18.9
19.4
34.2
2.9
5.7
11.2
19.1
19.3
33.6
3.0
6.2
0.2
12.1
1
19.6
2
18.8
32.9
3.1
6.6
0.2
11.9
40
Conventions
double energyTable new double37
  • energyTable has 3 rows and 7 columns
  • The first row is accessed by energyTable00,
    energyTable01, etc.
  • The second row is accessed byenergyTable10,
    energyTable11, etc.
  • Each of these is a variable (double), that can be
    used anywhere an expression is allowed
  • YOU CANNOT WRITE energyTable1, 0!

41
Arrays of anything as data types a few examples
  • Notice that double (like int ) is a data
    type, used in the declaration, or used before a
    formal parameter in a method, etc.

int myNumberspublic void secondMethod(int
b) double energyTablepublic void
calculate(double q) Time
mySchedulepublic void addTime(Time c)

42
Visiting All Elements in a Two-Dimensional Array
  • We used a regular loop (while or for) to visit
    every element in a one-dimensional array
  • We use nested loops to visit every element in a
    two-dimensional array (or a three-dimensional
    array, etc.)

43
Example Reading in Values from the User to Fill
in energyTable
final int NUM_SOURCES 7, NUM_YEARS
3double energyTable new
doubleNUM_YEARSNUM_SOURCESSimpleInput sinp
new SimpleInput(System.in)for (int y 0 y lt
NUM_YEARS y) for (int s 0 s lt
NUM_SOURCES s) energyTableys
sinp.readDouble( )
44
Tracing the Input of Data
for (int y 0 y lt NUM_YEARS y) for (int s
0 s lt NUM_SOURCES s) energyTableys
sinp.readDouble( )
  • y 0 s 0, 1, 2, 3, 4, 5, 6
  • y 1 s 0, 1, 2, 3, 4, 5, 6
  • y 2 s 0, 1, 2, 3, 4, 5, 6

45
Remember We Can Declare and Initialize an Array
All at Once
  • Arrays can be initialized by giving a list of all
    their elementsint primes 2, 3, 5, 7, 11,
    13, 17, 19, 23, 29
  • The declaration is on the left side of the
    assignment
  • No explicit creation of the object is necessary
    Java handles it automatically
  • It must be done in a single line this is
    illegalint primesprimes 2, 3, 5, 7, 11,
    13, 17, 19, 23, 29

46
We Can Do the Same Thing with Two-Dimensional
Arrays
  • We could writedouble energyTable
    18.9, 19.4, 34.2, 2.9, 5.7, 0.3,
    11.2, 19.1, 19.3, 33.6, 3.0, 6.2, 0.2,
    12.1, 18.8, 19.6, 32.9, 3.1, 6.6, 0.2,
    11.9
  • The proper number of array elements is
    automatically allocated and initialized

47
Two-Dimensional Arrays are Arrays of Arrays
  • In Java, a two-dimensional array is actually an
    array of arrays
  • In other words, its a one-dimensional array
    whose elements are (references to) other one
    dimensional arrays

48
What That energyTable Really Is
18.9
19.4
34.2
2.9
5.7
0.3
11.2
0
1
19.1
19.3
33.6
3.0
6.2
0.2
12.1
2
18.8
19.6
32.9
3.1
6.6
0.2
11.9
All (4) arrays are stored in the heap.
49
An Array of Arrays
  • When we writedouble energyTableenergyTab
    le new doubleNUM_YEARSNUM_SOURCES
  • It is actually a shorthand way of
    writingdouble energyTableenergyTable
    new doubleNUM_YEARS for (int i 0 i lt
    NUM_YEARS i) energyTablei new
    doubleNUM_SOURCES

50
Separate Arrays,Separate Declarations
energyTable new doubleNUM_YEARS
The length of the rows need not be declared at
the same time as the length of the columns
These will (eventually) hold references to
one-dimensional arrays of doubles
0
1
energyTable
2
heap
51
Each of the Arrays Has its Own Public Attribute
length
  • energyTable.length is 3

0
1
2
energyTable
heap
52
Once the Columns have been Declared
  • energyTable0.length is 7

18.9
19.4
34.2
2.9
5.7
0.3
11.2
0
1
19.1
19.3
33.6
3.0
6.2
0.2
12.1
2
18.8
19.6
32.9
3.1
6.6
0.2
11.9
53
An Example of Using length to Input
Two-Dimensional Array Values
  • If we had an int array called a, we could
    use the following to input its valuesfor (int
    row 0 row lt a.length row) for (int col
    0 col lt arow.length col)
    System.out.print(Enter value
    ) arowcol sinp.readInt( )

54
A Two Dimensional Array Can be Ragged (rows of
different lengths)
  • We can write int a new int3 for
    (int i 0 i lt 3 i) ai new inti
    1to get the ragged array on the next slide
  • This is useful for some applications (e.g.,
    keeping track of batters in baseball game)

55
The Ragged Array from the Previous Slide
Higher dimensional arrays (3-dimensional,4-dimens
ional, etc.) are also possible, of course
0
1
2
a
Write a Comment
User Comments (0)
About PowerShow.com