Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Similar documents
Example: Monte Carlo Simulation 1

Some Sample AP Computer Science A Questions - Solutions

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

COP 4516: Math for Programming Contest Notes

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

COMP-202 Unit 4: Programming with Iterations

Controls Structure for Repetition

Chapter 4: Control structures. Repetition

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 4: Control structures

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Question 1 (10 points) Write the correct answer in each of the following: a) Write a Processing command to create a canvas of 400x300 pixels:

Assignment 2.4: Loops

Warmup : Name that tune!

LOOPS. Repetition using the while statement

Repetition, Looping. While Loop

Write a program which converts all lowercase letter in a sentence to uppercase.

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Top-Down Program Development

CompSci 125 Lecture 11

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

AP COMPUTER SCIENCE A

1. Find the output of following java program. class MainClass { public static void main (String arg[])

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

First Java Program - Output to the Screen

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CS 101 Spring 2007 Midterm 2 Name: ID:

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Iteration statements - Loops

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CS111: PROGRAMMING LANGUAGE II

Control Structures: if and while A C S L E C T U R E 4

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

CS 101 Fall 2006 Midterm 3 Name: ID:

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

CSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona

Course Outline. Introduction to java

APCS Semester #1 Final Exam Practice Problems

STUDENT LESSON A12 Iterations

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

CS141 Programming Assignment #6

Repetition CSC 121 Fall 2014 Howard Rosenthal

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Oct Decision Structures cont d

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Chapter 6 Parallel Loops

CSc 520 Principles of Programming Languages

Java GUI Test #1 Solutions 7/10/2015

CIS 110: Introduction to Computer Programming

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Decisions in Java IF Statements

Chapter 4 Introduction to Control Statements

Unit 1 Lesson 4. Introduction to Control Statements

Ch. 6. User-Defined Methods

AP Computer Science Unit 3. Programs

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Last Class. While loops Infinite loops Loop counters Iterations

Programming Lecture 4

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Question 1 [20 points]

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Warm-Up: COMP Programming with Iterations 1

Technical Section. Lab 4 while loops and for loops. A. while Loops or for loops

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

The FacebookPerson Example. Dr. Xiaolin Hu CSC 2310, Spring 2015

Building Java Programs Chapter 2

Bjarne Stroustrup. creator of C++

CSE143 Notes for Monday, 4/25/11

1 Short Answer (10 Points Each)

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Claremont McKenna College Computer Science

Full file at

More on variables, arrays, debugging

CP122 CS I. Iteration

CSE 114 Computer Science I

Public-Service Announcements

1.3 Conditionals and Loops

Building Java Programs

CMPS 12A - Winter 2002 Final Exam A March 16, Name: ID:

Repetition Structures

Midterm Examination (MTA)

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Data Structures COE 312 ExamII Preparation Exercises

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Computer Science is...

Accelerating Information Technology Innovation

Problem Solving With Loops

Transcription:

Nested Loops To investigate nested loops, we'll look at printing out some different star patterns. Let s consider that we want to print out a square as follows: We know we can print out one line of this square as follows: System.out.println( ); Now, we can utilize the for loop to do this 5 times: for (int i=0; i<5; i=i+1) System.out.println( ); But, this would only work if we wanted a square of size 5. What if we wanted the user to choose the side length of the square? Then, when writing our program, we couldn't just do a single println with a fixed number of stars in it. Instead, we would have to utilize the user's input and print each star out one by one, so we printed out the right number of them on a single row. After that, we could advance to the next line. So, we would need a loop that went through each line we were printing. But, then, when we were printing a single line, we'd need another loop inside of the previous loop we wrote. This is what we call a nested loop structure.

Here is a full program that accomplishes our task: public class Square { public static void main( String args[] ) { // Get the user input. Scanner stdin = new Scanner(System.in); System.out.println("How big do you want your square?"); int n = stdin.nextint(); // Go through each row. for (int i=0; i<n; i++) { // Print exactly n stars on a single row. for (int j=0; j<n; j++) System.out.print("*"); // Advance to the next row. System.out.println(); The key here is that when i = 0, j cycles through the values 0, 1, 2,, n-1 and the print inside the j loop triggers exactly n times. Then, the newline prints. Then, i gets set to 1 and the whole process repeats. Now, consider the situation that you want to print out a slightly more difficult pattern, such as a triangle: * ** *** **** The trick for effectively using a for loop is to make use of the index variable. The index variable is the one initialized in the initialization statement. In our previous example this was the variable i. If you want to repeat your code exactly, several number of times, then you will not have i appear in the body of your for loop. However, most of the time you will actually want to make use of the index variable inside of your loop. In fact, to print out this triangle, we must use the index variable inside of our loop.

Our general construct will loop like the following: <Print out one line of the triangle> Now the problem we run into is that every line of the triangle is NOT the same. Thus, even though we must place the same code into the for loop body, it must execute differently every time. But, how is that possible??? The key is that if you place i in the for loop body, we know that i will take on different values for each iteration of the for loop. Thus, even though the code will look the exact same, it could potentially execute differently on different iterations. (We saw this earlier when we printed out the appropriate line number in the first example.) We can now refine our construct to look like the following: <Print out the line in the triangle with (i+1) stars in it.> Now, all we have to do is figure out how to print a line with exactly (i+1) stars. But wait, this is asking how to do something exactly a specific number of times! We know what we can use to do that a for loop! So our code will look like: for (int j=0; j <= i; j=j+1) { System.out.print( * ); Now, this isn t completely correct. The problem is that we do not have any println s. This means the cursor will never get to a second line and all the stars will be printed on the same line.

We know that we must advance to the next line once we are done printing the current line. We can do that as follows: for (int j=0; j <= i; j=j+1) { System.out.print( * ); System.out.println(); In this example, notice that the inner loop is dependent upon the loop index of the outer loop. This allows for different behavior when each different row prints. Printing Out all Prime Numbers in a Range In our next program with nested loops, we'll print out all of the prime numbers within a range of integers. Recall that a prime number is one that is 2 or greater which only has two divisors: 1 and itself. We can check for primality through trial division, making sure that each integer in between 2 and n-1, inclusive do NOT divide evenly into n. As previously discussed, we can use the mod operator to check divisibility. In this program, we'll prompt the user to enter in a low and high bound, and then we'll print out all of the primes between low and high, inclusive. Our strategy is as follows: 1. Get the user input. 2. Set up a loop that goes from low to high. 3. Inside that loop, set up the mechanism to check the current number for primality.

public class PrimeRange { public static void main( String args[] ) { // Get the low and high bounds for the prime search. Scanner stdin = new Scanner(System.in); System.out.println("Enter the low and high bounds."); int low = stdin.nextint(); int high = stdin.nextint(); System.out.print("The primes from "+low+" to "+high+" are "); // Try each number in range for primality. for (int i=low; i<=high; i++) { // Now, try dividing i by each relevant potential divisor. boolean isprime = true; for (int div=2; div<i; div++) if (i%div == 0) isprime = false; // Only print if none of the trial divisions worked. if (isprime) System.out.print(i+" "); System.out.println(); Inside the outer loop(i), our goal is to determine if i is prime or not. Thus, we must try to divide i by 2, 3,, i-1. We use the loop variable div to accomplish this goal. If any of these values is a divisor of i, we simply note that i isn't prime by changing a boolean variable from true to false. Note: inside of the if, one could break out, since once we find a divisor, there is no point in checking future values.

Drawing a CheckerBoard in a GUI Now that you've been introduced to drawing objects onto a canvas using Java Swing, we can utilize nested loops to draw a checkerboard. A checkerboard is an design of 8 x 8 squares which are colored red and black, alternately. For this example, we are just going to modify the draw function to be different than the draw function from the assignment PaintStuff. First, we'll simply do a nested loop structure that emulates going through 8 rows and columns. NUMSQ is a constant set to 8. for (int i=0; i<numsq; i++) { for (int j=0; j<numsq; j++) { One key question is how to decide what color to make a square. If the top left square is red, then the square directly to its right and below are black, and then the same logic can be applied to those two squares. What we see is that if i+j is even, then the square is red and if i+j is odd, the square is black. Notice that whenever we move right or down, we change the sum i+j by 1, because we are adding 1 to either i or j by moving right or down. Thus, if we are on an even sum square and it's red, we are guaranteed to move to a black square by changing our parity of the sum from even to odd. The argument works the other way around when moving from a black square. So, we can set our color as follows, right inside of the loop: for (int i=0; i<numsq; i++) { for (int j=0; j<numsq; j++) { if ((i+j)%2 == 0) g.setcolor(color.red); else g.setcolor(color.black); Finally, we must draw a filled rectangle. To do this, let's introduce some more constants: final public static int SQSIZE = 50; final public static int OFFX = 45; final public static int OFFY = 35; SQSIZE is the number of pixels on the side of each individual square, OFFX is the offset in X from the left side of the display and OFFY is the offset in Y from the top of the display. When i and j are zero, our top left pixel value is simply (OFFX, OFFY). As i and j change, we just add the appropriate multiple of SQSIZE to our offset. Here is the full draw method:

public void draw(graphics g) { g.setcolor(this.backgroundcolor); g.fillrect(0, 0, SCRSIZE, SCRSIZE); g.setcolor(this.charactercolor); for (int i=0; i<numsq; i++) { for (int j=0; j<numsq; j++) { if ((i+j)%2 == 0) g.setcolor(color.red); else g.setcolor(color.black); g.fillrect(sqsize*i+offx, SQSIZE*j+OFFY, SQSIZE, SQSIZE);