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

Similar documents
CS 112 Introduction to Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

Admin. CS 112 Introduction to Programming. Recap. Example: Nested Loop. Example: Rewrite

Building Java Programs

Topic 6 loops, figures, constants

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

Building Java Programs

Garfield AP CS. Graphics

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

Topic 6 Nested for Loops

Repetition with for loops

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

Building Java Programs Chapter 2

Building Java Programs

Topic 8 graphics. -mgrimes, Graphics problem report 134

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

Building Java Programs Chapter 2

Building Java Programs

Using Graphics. Building Java Programs Supplement 3G

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Topic 8 Graphics. Margaret Hamilton

CS111: PROGRAMMING LANGUAGE II

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

Lecture 5: Methods CS2301

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CS 112 Introduction to Programming

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Primitive data, expressions, and variables

Building Java Programs

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

CIS 110: Introduction to Computer Programming

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

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

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

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Exercise (Revisited)

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

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

CS Problem Solving and Object-Oriented Programming

CS 112 Introduction to Programming

Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

Chapter 4: Control structures. Repetition

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Chapter 7 User-Defined Methods. Chapter Objectives

EECS168 Exam 3 Review

Chapter 4: Control structures

CSc 110, Autumn 2016 Lecture 6: Parameters. Adapted from slides by Marty Stepp and Stuart Reges

AP CS Java Syntax Summary: (version 3)

Building Java Programs

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Building Java Programs

Building Java Programs

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: OOP. Math.random() Design. Static Math.random() method vs Random Objects

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

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Topic 9 More Graphics. Based on slides bu Marty Stepp and Stuart Reges from

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS1150 Principles of Computer Science Methods

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts

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

Instructor: Eng.Omar Al-Nahal

CS 112 Introduction to Programming

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Lecture Static Methods and Variables. Static Methods

1 Lexical Considerations

Computer Science is...

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Computer Science is...

Example: Monte Carlo Simulation 1

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

Research Group. 2: More types, Methods, Conditionals

CIS 110: Introduction to Computer Programming

AP CS Java Syntax Summary: (version 4)

McGill University School of Computer Science COMP-202A Introduction to Computing 1

} Each object in a Java program has an identifier (name) } This includes:

Lecture 13: Two- Dimensional Arrays

Array. Prepared By - Rifat Shahriyar

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Transcription:

Admin CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu q PS1 We encourage that you go over any issues with any of the teaching staff q PS3 to be posted Thursday morning q Coding style reviews led by Debayan 5-6pm today @ DL 220 q Informal lunch together at Commons This Friday at 12:40 pm Next Thursday 2 Recap: Code Style Counting down or up is mostly a personal style. Recap: Code Style Minimize # magic numbers. final int N = 10; for (int i = N; i >= 1; i--) { System.out.print(i +, ); final int N = 10; System.out.print(N+1-i +, ); 3 for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); Convey your intention to final int N = 10; the computer to help you. System.out.print(N+1-i +, ); 4 Counting Down: Code Puzzle Counting Down: Code Puzzle What if we want to print out the values of N and i after the loop: final int N = 10; System.out.print(N+1-i +, ); System.out.println( N = + N);? System.out.println( Final i = + i);? % javac CountDownValue.java CountDownValue.java:25: cannot find symbol symbol : variable i location: class CountDownValue System.out.println( "Final i = " + i ); ^ 1 error 1

Variable Scope Variable Scope q Scope: The part of a program where a variable exists. q Basic rule: from its declaration to the end of the enclosing { braces q Examples A variable declared in a for loop exists only in that loop. A variable declared in a specific method exists only in that method. A variable declared not inside any method but in a class is said to have class scope. i's scope public class CountDown { static int N = 10; public static void main(string[] args) { countdown(); public static void countdown() { int sum = 0; System.out.println( N + 1 i ); sum += i; System.out.println( N: + N); System.out.println( Sum: + sum); end of countdown end of class sum's scope N s scope Why Scope? Loop Example q Encapsulation e.g., different methods can use the same variable name without the need for coordination many analogies: folders allow same file name so long in different folders q Does the following code work? public static void main() { for (int i = 1; i <= 10; i++) { System.out.print( 11-i + ); public static void amethod() { int x = 1; public static void bmethod() { int x = 2; for (int i = 1; i <= 10; i++) { System.out.print(11 i + ); Output: 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 Loop Example Nested Loop q Does the following code work? for (int set = 1; set <= 5; set++) { for (int rps = 1; rps <= set; rps++) { System.out.print("*"); Output: * ** *** **** ***** for (int set = 1; set <= 5; set++) { for (int rps = 1; rps <= set; rps++) { System.out.print("*"); q A loop inside another loop is said to form a nested loop q The #loop times of the inner loop can depend on the outer loop variable 2

Practice: Nested for loop example q What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); q Output: 1 22 333 4444 55555 Practice: Nested for loop example q What is the output of the following nested for loops? for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(i*j + t ); Nested Loop Design Example: Drawing A Complex Pattern q Use nested for loops to draw ASCII X q A size SIZE ASCII X has 2 * SIZE rows q Why draw ASCII art? Real graphics will require some finesse (shortly) ASCII art has complex patterns Can focus on the algorithms SIZE 4 SIZE 3 SIZE 5 Design Decomposition 1. Bound ==, (SIZE 2)*2 spaces, == 2. Top half (V) 3. Bottom half (top half upside-down) 4. Bound SIZE 4 SIZE 3 SIZE 5 Top Half (V) Outer and inner loop q Observation: V can be produced using a nested for loop outer loop (loops SIZE 1 times) q First write the outer loop, from 1 to the number of lines. for (int line = 1; line <= SIZE-1; line++) {... q Now look at the line contents. Each line has a pattern: some white space some white space 1 2 3 3

Final Pseudo Code 1. Bound ==, (SIZE 2)*2 spaces, == 2. for line = 1 to SIZE -1 line spaces 2 (SIZE 2) + 2 2 * line spaces 3. for line = 1 to SIZE 1 SIZE line spaces (line 1) * 2 spaces 4. Bound 1 2 3 1 2 3 Implementation Problem 1. Bound ==, (SIZE 2)*2 spaces, == 2. for line = 1 to SIZE -1 line spaces 2 SIZE 2 2 * line spaces 3. for line = 1 to SIZE 1 SIZE line spaces (line 1) * 2 spaces 4. Bound Drawing spaces is a reusable function, but need to draw different numbers of spaces. Method Parameterization q Specify a parameter to control the behavior of a method q Methods with parameters solve an entire class of similar problems q Redundancy removalabstraction through generalization The more general a building block, the easier to reuse it We will learn more techniques on generalizationabstraction Parameterization q parameter: A value passed to a method by its caller, e.g., When declaring a method, we will state that it requires a parameter for the number of spaces. When calling the method, we will specify the number. 21 Declaring a Parameter public static void <method_name> (<type> <param_name>) { <statement>(s); q The parameter is called the formal argument q Example: public static void saypasswcode(int code) { System.out.println("The passcode is: " + code); How Parameters are Passed q When a method with a formal argument is called: A value is passed to the formal argument The passed value is called the actual argument The method's code executes using that value. public static void main(string[] args) { chant(3); chant(3+4); 37 public static void chant(int times) { for (int i = 1; i <= times; i++) { System.out.println("Just a salad..."); 4

Common Errors Method Exercise q If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. chant(); ERROR: parameter value required q Exercise: Design and implement the DrawX program. q The value passed to a method must be of the correct type. chant(3.7); ERROR: must be of type int Multiple Parameters q A method can accept multiple parameters. (separate by, ) When calling it, you must pass values for each parameter. q Declaration: public static void <name>(<type> <name>,..., <type> <name>) { <statement>(s); q Call: <name>(<exp>, <exp>,..., <exp>); Multiple Parameters Example public static void main(string[] args) { printnumber(4, 9); printnumber(17, 6); printnumber(8, 0); printnumber(0, 8); public static void printnumber(int number, int count) { for (int i = 1; i <= count; i++) { System.out.print(number); Output: 444444444 171717171717 00000000 Multiple Parameter Invocation q Corresponding actual argument in the invocation is copied into the corresponding formal argument printnumber(2, 5); public static void printnumber(int number, int count) { equiv: number = 2; count = 5; for (int i = 1; i <= count; i++) { System.out.print(number); 29 5

Java Graphics Methods Access Methods q Java provides a large number of methods for graphics We use graphics to see many examples of methods with parameters and loops q To access a method or class variable defined in another class, using the <class-name>.<method-name>( ), for example, StdDraw.setCanvasSize(100, 100); q To simplify the usage the Graphics methods, multiple libraries are provided Textbook: define class DrawingPanel, which contains many Graphics methods Sedgewick & Wayne book: defines class StdDraw, which contains many Graphics methods http:introcs.cs.princeton.edujavastdlibjavadocstddraw.html 31 32 StdDraw Methods Color and Class Constants q class constant: A static class variable with a fixed value value can be set only at declaration; cannot be reassigned q Syntax: public static final type name = value; in class scope name is usually in ALL_UPPER_CASE Examples: public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE = 3.5; public static final int SSN = 658234569; 33 Color Example: Using Colors q Java predefine many class constants in the Color class: Color.CONSTANT_NAME where CONSTANT_NAME is one of: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW q Pass a Color to StdDraw's setpencolor method Subsequent shapes will be drawn in the new color. StdDraw.setPenColor(Color.BLACK); StdDraw.filledRectangle(10, 30, 100, 50); StdDraw.line(20, 0, 10, 30); StdDraw.setPenColor(Color.RED); StdDraw.filledEllipse(60, 40, 40, 70); http:download.oracle.comjavase6docsapijavaawtcolor.html See SimplePanel.java 6

Exercise 7