Topic 6 Nested for Loops

Similar documents
Repetition with for loops

Building Java Programs

Primitive data, expressions, and variables

Topic 6 loops, figures, constants

Building Java Programs Chapter 2

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 112 Introduction to Programming

Chapter Legal intliterals: 22, 1, and d Results of intexpressions:

Admin. CS 112 Introduction to Programming. Counting Down: Code Puzzle. Counting Down: Code Puzzle

CS 112 Introduction to Programming

Warmup : Name that tune!

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Building Java Programs

Building Java Programs

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CIS 110: Introduction to Computer Programming

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

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COMP-202 Unit 4: Programming with Iterations

Repetition CSC 121 Fall 2014 Howard Rosenthal

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS 161: Object Oriented Problem Solving

Exercise (Revisited)

Topic 5 for loops and nested loops

Building Java Programs

Control Structures in Java if-else and switch

CS 161: Object Oriented Problem Solving

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

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

Week 2. expressions, variables, for loops

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Contents. 8-1 Copyright (c) N. Afshartous

CIS 110: Introduction to Computer Programming

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

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

CS 161: Object Oriented Problem Solving

Lesson 36: for() Loops (W11D1)

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

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

CS1150 Principles of Computer Science Loops (Part II)

Chapter 4: Control structures. Repetition

Example: Monte Carlo Simulation 1

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 4: Control structures

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

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

CS 161: Object Oriented Problem Solving

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

TESTING AND DEBUGGING

Nested Loops. A loop can be nested inside another loop.

AP COMPUTER SCIENCE A

Iteration statements - Loops

King Saud University College of Computer and Information Sciences Computer Science Department

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CS 112 Introduction to Programming

CS 112 Introduction to Programming

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

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

CS 112 Introduction to Programming

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

CIS 110 Introduction To Computer Programming. October 5th, 2011 Exam 1. Answer key for review problems

CIS March 1, 2018

1.3 Conditionals and Loops

Top-Down Program Development

Lecture Set 4: More About Methods and More About Operators

Full file at

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

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

1.3 Conditionals and Loops

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

CONDITIONAL EXECUTION

Warm-Up: COMP Programming with Iterations 1

Over and Over Again GEEN163

class objects instances Fields Constructors Methods static

Introduction to the Java Basics: Control Flow Statements

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Computer Science is...

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

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

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

Spring University of New Mexico CS152 Midterm Exam. Print Your Name

Bjarne Stroustrup. creator of C++

Introduction to Computer Programming

Primitive Data, Variables, and Expressions; Simple Conditional Execution

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

CIS 110 Introduction To Computer Programming. October 5th, 2011 Exam 1. Answer key

Control Structures in Java if-else and switch

CIS 110 Introduction To Computer Programming. October 5th, 2011 Exam 1. Review problems

Topic 7 parameters. Based on slides from Marty Stepp and Stuart Reges from

Repetition, Looping. While Loop

Some Sample AP Computer Science A Questions - Solutions

*Java has included a feature that simplifies the creation of

Transcription:

Topic 6 Nested for Loops "Complexity has and will maintain a strong fascination for many people. It is true that we live in a complex world and strive to solve inherently complex problems, which often do require complex mechanisms. However, this should not diminish i i our desire for elegant solutions, which h convince by their clarity and effectiveness. Simple, elegant solutions are more effective, but they are harder to find than complex ones, and they require more time, which we too often believe to be unaffordable " -Niklaus Wirth Based on slides for Building Java Programs by Reges/Stepp, found at http://faculty.washington.edu/stepp/book/ pp CS305j Introduction to Computing Nested For Loops 1

Nested for loops 8A for loop can contain any kind of statement in its body, including another for loop. The inner loop must have a different name for its loop counter variable so that t it will not conflict with the outer loop. 8nested loop: Loops placed inside one another, creating a loop of loops. for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { System.out.println("six"); Output: six six six six six six CS305j Introduction to Computing Nested For Loops 2

More nested for loops 8All of the statements in the outer loop's body are executed 5 times. The inner loop runs 10 times for each of those 5 times, for a total of 50 numbers printed. for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.print((i * j) + " "); System.out.println(); // to end the line Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 CS305j Introduction to Computing Nested For Loops 3

Nested for loop exercise 8What t is the output t of the following nested for loop? for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 5; j++) { System.out.print("*"); System.out.println(); 8Output? 8Do you really need a nested for loop in this case? CS305j Introduction to Computing Nested For Loops 4

Nested for loop exercise 8What is the output of the following nested for loop? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); System.out.println(); 8Output: * ** *** **** ***** ****** CS305j Introduction to Computing Nested For Loops 5

Nested for loop exercise 8What t is the output t of the following nested for loop? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); System.out.println(); 8Output? CS305j Introduction to Computing Nested For Loops 6

Nested for loop exercise 8Create a nested for loops produce the following output....1...22..333.4444 55555 CS305j Introduction to Computing Nested For Loops 7

Nested for loop exercise 8A for loop can have more than one loop nested in it. 8What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= (5 - i); j++) { System.out.print(" "); for (int k = 1; k <= i; k++) { System.out.print(i); System.out.println(); 8Answer: 1 22 333 4444 55555 CS305j Introduction to Computing Nested For Loops 8

Common nested loop bugs 8It is a common bug to accidentally type the wrong loop counter variable, which can lead to incorrect behavior. What is the output of the following nested loops? for (int i = 1; i <= 10; i++) { for (int j = 1; i <= 5; j++) { System.out.print(j); System.out.println(); What tis the output tof fthe following nested dl loops? for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; i++) { System.out.print(j); System.out.println(); CS305j Introduction to Computing Nested For Loops 9

How to comment: for loops 8 Place a comment on complex loops explaining what they do from a conceptual standpoint, not the mechanics of the syntax. Bad: // This loop repeats 10 times, with i from 1 to 10. for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; j++) { // loop goes 5 times System.out.print(j); // print the j System.out.println(); Better: // Prints 12345 ten times on ten separate lines. for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; j++) { System.out.print(j); System.out.println(); // end the line of output CS305j Introduction to Computing Nested For Loops 10

Variable Scope CS305j Introduction to Computing Nested For Loops 11

Variable scope 8scope: The portion of a program where a given variable exists. A variable's scope is from its declaration to the end of the block (pair of {braces) in which it was declared. If a variable is declared in a for loop (including the <initialization> or the loop's <statement(s)>, it exists until the end of that for loop. If a variable is declared in a method, it exists only in that method, until the end of the method. public static void main(string[] args) { int x = 3; for (int i = 1; i <= 10; i++) { System.out.print(x); // i no longer exists here // x ceases to exist here CS305j Introduction to Computing Nested For Loops 12

Scope and using variables 8It is a syntax error to try to use a variable outside of its scope. public static void main(string[] args) { example(); System.out.println(x); // syntax error for (int i = 1; i <= 10; i++) { int y = 5; System.out.println(y); System.out.println(y); // syntax error public static void example() { int x = 3; System.out.println(x); CS305j Introduction to Computing Nested For Loops 13

Overlapping scope 8It is syntactically legal to declare variables with the same name, as long as their scopes do not overlap: public static void main(string[] args) { int x = 2; for (int i = 1; i <= 5; i++) { int y = 5; System.out.println(y); for (int i = 3; i <= 5; i++) { int y = 2; int x = 4; // illegal System.out.println(y); public static void anothermethod() { int i = 6; int y = 3; System.out.println(i + ", " + y); CS305j Introduction to Computing Nested For Loops 14

Problem: redundant values 8Often in our programs we will have certain values (sometimes called magic numbers) that are used throughout the program: public static void main(string[] args) { printtop(); printbottom(); public static void printtop() p() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) { System.out.print(j); System.out.println(); public static void printbottom() { for (int i = 3; i >= 1; i--) { for (int j = i; j >= 1; j--) { System.out.print(3); System.out.println(); CS305j Introduction to Computing Nested For Loops 15

Global constants 8global (class) constant: A special kind of variable that can be seen throughout the program. The value of a constant can only be set once. It can not be changed while the program is running. 8 Global constant syntax: public static final <type> <name> = <value> ; Constants' names are usually written in ALL_UPPER_CASE. Examples: public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE RATE = 3.5; public static final int SSN = 658234569; CS305j Introduction to Computing Nested For Loops 16

Global constant example 8 Making the 3 a global constant removes the redundancy: the global constant is declared outside methods, but inside the program, public class PrintFigure{ public static final int MAX_VALUE = 3; public static void main(string[] args) { printtop(); printbottom(); public static void printtop() { for (int i = 1; i <= MAX_VALUE; i++) { for (int j = 1; j <= i; j++) { System.out.print(j); System.out.println(); public static void printbottom() { for (int i = MAX_VALUE; i >= 1; i--) { for (int j = i; j >= 1; j--) { System.out.print(MAX_VALUE); System.out.println(); CS305j Introduction to Computing Nested For Loops 17

Another example: figure 8Consider the task of drawing the following figure: +/\/\/\/\/\+ +/\/\/\/\/\+ +/\/\/\/\/\+ +/\/\/\/\/\+ 8Each figure is strongly tied to the number 5 (or a multiple such as 10...) 8See code for drawing these figures. CS305j Introduction to Computing Nested For Loops 18

Some repetitive code 8Note the repetition of numbers based on 5 in the code: public static void drawfigure1() { drawplusline(); drawbarline(); drawplusline(); public static void drawplusline() { System.out.print("+"); for (int i = 1; i <= 5; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawbarline() { System.out.print(" "); for (int i = 1; i <= 10; i++) { System.out.print(" "); System.out.println(" "); Output: +/\/\/\/\/\+ +/\/\/\/\/\+ It would be cumbersome to resize the figure such as by changing all the 5s into 8s. CS305j Introduction to Computing Nested For Loops 19

A failed attempt to fix it 8AA normal variable cannot be used to fix the problem, because it is out of scope: public static void main(string[] args) { int width = 5; drawfigure1(); public static void drawfigure1() { drawplusline(); drawbarline(); drawplusline(); public static void drawplusline() { System.out.print("+"); for (int i = 1; i <= width; i++) { // ERROR System.out.print("/\\"); System.out.println("+"); CS305j Introduction to Computing Nested For Loops 20

Fixing our code with constant 8A A global constant will fix the "magic number" problem: public static final int FIGURE_WIDTH = 5; public static void main(string[] args) { drawfigure1(); public static void drawfigure1() { drawplusline(); System.out.print(" "); for (int i = 1; i <= 2 * FIGURE_WIDTH; i++) { System.out.print(" "); System.out.println(" "); drawplusline(); CS305j Introduction to Computing Nested For Loops 21