nested loops. nested loops just as a selection structure can be nested within another selection...

30
Nested Loops

Upload: ruth-mcbride

Post on 17-Dec-2015

277 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Nested Loops

Page 2: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Nested loops

• Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

• When one loop is nested within another, each iteration of the “outer” loop contains several iterations of the “inner” loop

Page 3: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Example – multiplication table

• Suppose you wanted to print a multiplication table of the sort your instructor was forced to memorize in second grade

• Each line and column of the table has a number between 2 and 15 as its heading; the entries at each row/column intersection are the results when the row heading is multiplied by the column heading

Page 4: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Multiplication table program output – an excerpt

2 3 4 5 6 7 8 9 ------------------------------------------------- 2| 4 6 8 10 12 14 16 18 3| 6 9 12 15 18 21 24 27 4| 8 12 16 20 24 28 32 36 5| 10 15 20 25 30 35 40 45 6| 12 18 24 30 36 42 48 54 7| 14 21 28 35 42 49 56 63 8| 16 24 32 40 48 56 64 72 9| 18 27 36 45 54 63 72 81

Page 5: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Formatting output

• In order to print the table with even spacing, we need a systematic way to format the output

• One approach would be to precede each value to be printed with a String consisting of a fixed number of spaces

• The textbook describes another option, using an object of the Formatter class

• Yet another, illustrated in the next several slides, uses yet another output method from System.out: printf (short for print formatted)

Page 6: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Formatting Output

• We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows the field width of 6.

Page 7: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

The printf method

• The printf method takes a minimum of one argument, and may take several

• The first argument is the control string, which specifies the format for the remaining arguments, if any

• If the control string is the only argument, its contents are an ordinary string literal, and printf works exactly like print

• If there are additional arguments, they follow the control string

Page 8: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Control Strings

• Integers%<field width>d

• Example:System.out.printf(“The result is: %5d\n”, 100);

Output:

The result is: 100

• In the example above, the number is printed right-justified in a field of 5 spaces

Page 9: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Control strings

• Real Numbers%<field width>.<decimal places>f

• Example:System.out.printf(“You owe: $%7.2f\n”, 3.15679e2);

Output:You owe: $ 315.68

• In the example, the specified field width was one space wider than required to print the number with 2 decimal places

• If you specify a field width that is too narrow for the output, the field width value is simply ignored

Page 10: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Control strings

• Strings%s

• Example:System.out.printf("%10s%10s%10s\n",

"Yours", "Mine", "Ours");

• Output: Yours Mine Ours

Page 11: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Multiplication table - headings

Print the numbers between 2 and 15, spaced evenlyPrint a series of hyphens in a single linePlace an end of line character after each of the lines above

public void printHeadings () { System.out.printf ("%8s", ""); for (int x=2; x<=15; x++) System.out.printf ("%5d", x); System.out.print("\n"); for (int y=0; y<80; y++) System.out.print("-"); System.out.print("\n");}

Page 12: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Multiplication table

• Outer loop controls the number of lines to be printed; contains:– Inner loop– Line to print a newline character

• Inner loop controls the contents of each line– Row heading– Product of current row & column headings

Page 13: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Code to print table

public void drawTable () { for (int x = start; x <= size; x++) { for (int y = start; y <= size; y++) { if (y==start) System.out.printf("%7d%s", x, "|"); System.out.printf("%5d", (x * y)); } System.out.printf("\n"); } }

Page 14: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Tracing nested loops

• Write down value of each loop counter as it changes during loop execution

• If any output or change in other variable occurs, write this down next to the tally of loop counters

Page 15: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Example – multiplication table

x y output

2 2 43 64 8… 15 … 3016

3 2 6 3 9 4 12… 15 … 4516

4 2 8… 15 … 6016

.

.

.15 2 30 … 15 … 22516

16

Page 16: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

initialize outer loop

while ( outer loop condition )

{ . . .

initialize inner loop

while ( inner loop condition )

{

inner loop processing and update

}

. . .}

Pattern of a Nested Loop

Page 17: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Example Problem

Suppose we have data in the form below, involving several ID strings. For each ID string, a variable number of readings have been recorded; the number of readings for each ID is shown in the howMany column

ID howMany Readings

4567 5 180 140 150 170 1202318 2 170 2105232 3 150 151 151

Page 18: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

4567 1522318 1905232 151 . . .There were 15 data sets on file

Our goal: read in the data and display a summary chart like the

one shown below:

ID Average

Page 19: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Algorithm

• initialize count to 0• read first ID and howMany• while not at end of data

– increment count– display ID– use a count-controlled loop to read

and sum up this ID’s howMany readings

– calculate and display average for ID– read next ID and howMany

• display count

Page 20: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

import java.util.*;import javax.swing.*;

public class NestLoop { public static void main (String [] args) { int total = 0; // total for all IDs int thisID, // current ID number howMany, // number of readings for current ID reading, // current reading idTotal, // total for current ID number idCount, // counter for inner loop again; // outer loop control variable double average; // average for current ID String input; // gets data from user for processing

Page 21: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

System.out.printf("%s%13s\n", "ID Number","Average");

do { // start of outer loop

input = JOptionPane.showInputDialog(null,"Enter ID number");

thisID = Integer.parseInt(input); input = JOptionPane.showInputDialog(null,

"How many readings for this ID?"); howMany = Integer.parseInt(input); idTotal = 0; idCount = 0; total++;

Page 22: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

// inner loop – process all readings for this ID

while (idCount < howMany) {

input = JOptionPane.showInputDialog(null,

"Enter reading");

reading = Integer.parseInt(input);

idTotal += reading;

idCount++;

}

Page 23: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

// continuation of outer loop

average = (double)idTotal / howMany; System.out.print("" + thisID); System.out.printf("%17.2f\n", average); again = JOptionPane.showConfirmDialog(null,

"Any more data?", "More Data",

JOptionPane.YES_NO_OPTION); } while (again == JOptionPane.YES_OPTION); System.out.println ("Total of " + total +

" records were processed."); }}

Page 24: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Using nested loops to draw figures (ASCII art)

• Drawing figures can illustrate how nested loops work

• Keep in mind the principle: outer loop controls number of lines, inner loop controls content of lines

Page 25: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Trace the following loop

int x, y;for(x=0; x<5; x++){

for(y=5; y>0; y--)System.out.print(“* ”);

System.out.print(“\n”);}

Page 26: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Trace the following loopimport java.util.*;

public class triangle { public static void main (String [] args) { int x, y, z, height; Scanner kb = new Scanner(System.in); System.out.print ("Enter height: "); height = kb.nextInt(); for (x=0; x<height; x++) { for (y=height; y>x; y--) System.out.print(" "); for (z=0; z<=x; z++) System.out.print("* "); System.out.print("\n"); } }}

height = 4x y z0 4 3 2 1 0 0 11 4 3 2 1 0 1 22 4 3 2 0 1 2 33 4 3 0 1 2 3 4

Output: * * * * * * * * * *

• y loop prints spaces• z loop prints stars

Page 27: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Loop example with break statement

int x,y;for (x=1; x<5; x++){

for (y=1; y<5; y++){

if (y > x)break;

cout << “* ”;}cout << “\n”;}

}

OUTPUT:

** ** * ** * * *

Page 28: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Continue statement

• is valid only within loops

• terminates the current loop iteration, but not the entire loop

• in a For or While, continue causes the rest of the body statement to be skipped--in a For statement, the update is done

• in a Do-While, the exit condition is tested, and if true, the next loop iteration is begun

Page 29: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Loop example with continue

int x,y;for (x=1; x<5; x++){

for (y=1; y<5; y++){

if (y > x)break;

cout << “* ”;}if (x % 2)

continue;cout << “\n”;

}

OUTPUT

* * ** * * * * * *

Page 30: Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested

Loop Testing and Debugging

• test data should test all sections of program

• beware of infinite loops -- program doesn’t stop

• check loop termination condition, and watch for “off-by-1” problem

• use get function for loops controlled by detection of ‘\n’ character

• trace execution of loop by hand with code walk-through

• use a debugger to run program in “slow motion” or use debug output statements