Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Nested Loops

2 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

3 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

4 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

5 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)

6 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.

7 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

8 Control Strings Integers % 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

9 Control strings Real Numbers %. 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

10 Control strings Strings %s Example: System.out.printf("%10s%10s%10s\n", "Yours", "Mine", "Ours"); Output: Yours Mine Ours

11 Multiplication table - headings Print the numbers between 2 and 15, spaced evenly Print a series of hyphens in a single line Place 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"); }

12 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

13 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"); }

14 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

15 Example – multiplication table xyoutput 22 436364 8… 15… 3016 32 6 3 9 4 12… 15… 4516 42 8… 15 … 6016. 15 230 … 15 … 22516

16 initialize outer loop while ( outer loop condition ) {... initialize inner loop while ( inner loop condition ) { inner loop processing and update }... } Pattern of a Nested Loop

17 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 howManyReadings 4567 5180 140 150 170 120 23182170 210 52323150 151 151

18 4567152 2318190 5232151... 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

19 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

20 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

21 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++;

22 // inner loop – process all readings for this ID while (idCount < howMany) { input = JOptionPane.showInputDialog(null, "Enter reading"); reading = Integer.parseInt(input); idTotal += reading; idCount++; }

23 // 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."); }

24 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

25 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”); }

26 Trace the following loop import 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 = 4 x yz 0 4 3 2 1 00 1 1 4 3 2 10 1 2 2 4 3 20 1 2 3 3 4 30 1 2 3 4 Output: * * * * * * * * * * y loop prints spaces z loop prints stars

27 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: * * * * * *

28 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

29 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 * * * * * * * * * *

30 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


Download ppt "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."

Similar presentations


Ads by Google