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.

Slides:



Advertisements
Similar presentations
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Advertisements

Computer Science 1620 Loops.
1 Lecture 15 Chapter 6 Looping Dale/Weems/Headington.
1 Lecture 16 Chapter 6 Looping Dale/Weems/Headington.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Chapter 6 Looping Dale/Weems. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
Chapter 6 Repetition. Topics Some additional operators –increment and decrement –assignment operators Repetition –while –do-while –for Random numbers.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
1 Chapter 5 File Objects and Looping Statements (Some slides have been modified from their original format)
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
Chapter 6 Looping.
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Chapter 5 Loops.
Nested LOOPS.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 6 Looping. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition to.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Java Fundamentals 4.
Chapter 6 Looping.
Loops.
Chapter 5: Control Structures II
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
Looping.
Control Structure Senior Lecturer
Outline Altering flow of control Boolean expressions
The for-loop and Nested loops
Iteration: Beyond the Basic PERFORM
Control Statements Loops.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Introduction to Java Applications
Control Statements Loops.
Presentation transcript:

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

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 are additional arguments, they follow the control string

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

Control strings Real Numbers %. f Example: System.out.printf(“You owe: $%7.2f\n”, e2); Output: You owe: $ 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("%10s%10s%10s\n", "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 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"); }

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

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 xyoutput … 15… … 15… … 15 … … 15 … 22516

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

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

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

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

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

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

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

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

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