Introduction To Programming Instructor: Greg Shaw

Introduction To Programming Instructor: Greg Shaw

<p>Computer Programming I Instructor: Greg Shaw COP 2210 </p><p>Nested Loops</p><p>I. Definition</p><p>“A loop inside another loop”</p><p>II. Things to Know</p><p>1. Any kind of loop – for, while, or do-while – may be nested inside any other 2. Each nested loop must to have its own Loop Control Variable (LCV) 3. The inner loop is fully executed - from the initialization of the LCV until the boolean expression becomes false - on each iteration of the outer loop</p><p>III. Example</p><p> for (int times = 1 ; times <= 3 ; times++) { for (int hip = 1 ; hip <= 2 ; hip++) // * { System.out.print(“Hip, ”) ; // ** } System.out.println(“Hooray!”) ; // * }</p><p>* These two statements are in the outer loop, so will be executed 3 times - once for each value of times from 1 to 3</p><p>** This statement is in the inner loop, so will be executed 2 times - once for each value of hip from 1 to 2 - on each iteration of the outer loop. The total number of times executed = 3 * 2 = 6</p><p>OUTPUT Hip, Hip, Hooray! Hip, Hip, Hooray! Hip, Hip, Hooray!</p><p>IV. More Examples See TableTester.java on the class web site and GallopingDominoes.java and GallopingDominoes2.java on the lab web site V. Self-Check Questions</p><p> a. What is the output of this code segment?</p><p> for (int outer = 1 ; outer <= 3 ; outer++) { for (int inner = 1 ; inner <= 3 ; inner++) { System.out.println(outer + “ ” + inner) ;</p><p>} }</p><p> b. What about this one?</p><p> for (int i = 1 ; i <= 3 ; i++) { for (int j = 1 ; j <= i ; j++) { System.out.println(i + “ ” + j) ; } }</p><p> The answers are on the next page VI. Answers to Self-Check Questions</p><p> a.</p><p>1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3</p><p> b.</p><p>1 1 2 1 2 2 3 1 3 2 3 3</p>

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    4 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us