Nested Loops Nested loops Just as a selection
- Slides: 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 • When one loop is nested within another, each iteration of the “outer” loop contains several iterations of the “inner” loop
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
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
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)
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.
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 additional arguments, they follow the control string
Control Strings • Integers %<field width>d • Example: System. out. printf(“The result is: %5 dn”, 100); Output: The result is: 100 • In the example above, the number is printed right-justified in a field of 5 spaces
Control strings • Real Numbers %<field width>. <decimal places>f • Example: System. out. printf(“You owe: $%7. 2 fn”, 3. 15679 e 2); 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
Control strings • Strings %s • Example: System. out. printf("%10 s%10 sn", "Yours", "Mine", "Ours"); • Output: Yours Mine Ours
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 print. Headings () { System. out. printf ("%8 s", ""); for (int x=2; x<=15; x++) System. out. printf ("%5 d", x); System. out. print("n"); for (int y=0; y<80; y++) System. out. print("-"); System. out. print("n"); }
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
Code to print table public void draw. Table () { for (int x = start; x <= size; x++) { for (int y = start; y <= size; y++) { if (y==start) System. out. printf("%7 d%s", x, "|"); System. out. printf("%5 d", (x * y)); } System. out. printf("n"); } }
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
Example – multiplication table x y output 2 3 4. . . 15 2 3 4 … 15 16 2 … 15 16 4 6 8 … 30 6 9 12 … 45 8 … 60 2 30 16 … 15 16 … 225
Pattern of a Nested Loop initialize outer loop while ( outer loop condition ) { . . . initialize inner loop while ( inner loop condition ) { inner loop processing and update } . . . }
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 how. Many column ID 4567 2318 5232 how. Many 5 2 3 Readings 180 140 150 170 120 170 210 151 151
Our goal: read in the data and display a summary chart like the one shown below: ID Average 4567 152 2318 190 5232 151. . . There were 15 data sets on file
Algorithm • initialize count to 0 • read first ID and how. Many • while not at end of data – increment count – display ID – use a count-controlled loop to read and sum up this ID’s how. Many readings – calculate and display average for ID – read next ID and how. Many • display count
import java. util. *; import javax. swing. *; public class Nest. Loop { public static void main (String [] args) { int total = 0; // total for all IDs int this. ID, // current ID number how. Many, // number of readings for current ID reading, // current reading id. Total, // total for current ID number id. Count, // counter for inner loop again; // outer loop control variable double average; // average for current ID String input; // gets data from user for processing
System. out. printf("%s%13 sn", "ID Number", "Average"); do { // start of outer loop input = JOption. Pane. show. Input. Dialog(null, "Enter ID number"); this. ID = Integer. parse. Int(input); input = JOption. Pane. show. Input. Dialog(null, "How many readings for this ID? "); how. Many = Integer. parse. Int(input); id. Total = 0; id. Count = 0; total++;
// inner loop – process all readings for this ID while (id. Count < how. Many) { input = JOption. Pane. show. Input. Dialog(null, "Enter reading"); reading = Integer. parse. Int(input); id. Total += reading; id. Count++; }
// continuation of outer loop average = (double)id. Total / how. Many; System. out. print("" + this. ID); System. out. printf("%17. 2 fn", average); again = JOption. Pane. show. Confirm. Dialog(null, "Any more data? ", "More Data", JOption. Pane. YES_NO_OPTION); } while (again == JOption. Pane. YES_OPTION); System. out. println ("Total of " + total + " records were processed. "); } }
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
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”); }
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. next. Int(); 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 y 0 43210 1 4321 2 432 3 43 z 01 01234 Output: * * * * * • y loop prints spaces • z loop prints stars
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: * * * * *
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
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 * * * * *
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 “offby-1” problem • use get function for loops controlled by detection of ‘n’ character • trace execution of loop by hand with code walkthrough • use a debugger to run program in “slow motion” or use debug output statements
- Pseudocode nested loop example
- Nested loops storytelling
- Nested loops python
- N nested for loops
- How to break matlab loop
- Data types in database
- Is nested loops bad
- Plan de ejecucion oracle
- Lesson 13 bee nested loops
- Nested loops java
- Complexity of nested for loops
- For loop space complexity
- Break in python nested loop
- Nested selection structure
- Sequence structure adalah
- Nested selection structure
- Rewrite the final six lines of romeo and juliet
- Two way selection and multiway selection in c
- Similarities
- Stabilizing selection
- Two way selection and multiway selection in c
- K selection r selection
- Clumped dispersion
- Procedure of pure line selection
- Natural selection vs artificial selection
- Natural selection vs artificial selection
- Balancing selection vs stabilizing selection
- Artificial selection vs natural selection
- Forward path in signal flow graph
- For loop small basic
- Intestinal obstruction classification