Topic 6 loops, figures, constants

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

Building Java Programs Chapter 2

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

Building Java Programs Chapter 2

Topic 6 Nested for Loops

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

Building Java Programs

Primitive data, expressions, and variables

Repetition with for loops

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 112 Introduction to Programming

10/9/07. < Moo? > \ ^ ^ \ (oo)\ ( )\ )\/\ ----w

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

CS 112 Introduction to Programming

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

Topic 5 for loops and nested loops

clicker question Comments Using comments Topic 3 static Methods and Structured Programming

Building Java Programs

Topic 4 Expressions and variables

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

Recursion. Garfield AP Computer Science. As usual, significant borrowings from Stuart Reges and Marty Stepp at UW -- thanks!!

Building Java Programs

Week 2. expressions, variables, for loops

CIS 110: Introduction to Computer Programming

Topic 12 more if/else, cumulative algorithms, printf

Topic 3 static Methods and Structured Programming

Lecture 19: Recursion

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

CS 112 Introduction to Programming

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

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

Advanced if/else & Cumulative Sum

CS 112 Introduction to Programming

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

Building Java Programs

Topic 8 Graphics. Margaret Hamilton

Topic 8 graphics. -mgrimes, Graphics problem report 134

Building Java Programs

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

Topic 12 more if/else, cumulative algorithms, printf

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

CS 161: Object Oriented Problem Solving

Topic 21 arrays - part 1

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Chapter 5: Methods. Lecture 10

Warmup : Name that tune!

Controls Structure for Repetition

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

Topic 11 Scanner object, conditional execution

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

class objects instances Fields Constructors Methods static

CIS 110: Introduction to Computer Programming

Building Java Programs

Building Java Programs

Topic 13 procedural design and Strings

Computer Science is...

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

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

Exercise (Revisited)

CS 112 Introduction to Programming

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

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

CS 112 Introduction to Programming

Lecture 2: Operations and Data Types

AP Computer Science A Summer Assignment 2017

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

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

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Building Java Programs

Lab # 2. For today s lab:

CS 112 Introduction to Programming

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

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

Topic 14 while loops and loop patterns

CS 161: Object Oriented Problem Solving

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

STUDENT LESSON A12 Iterations

Java Bytecode (binary file)

Topic 11 Scanner object, conditional execution

Outline. CIS 110: Introduction to Computer Programming. Announcements. For Loops. Redundancy in Patterns. A Solution with Our Current Tools

CS111: PROGRAMMING LANGUAGE II

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

Introduction to the Java Basics: Control Flow Statements

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

CSE 143 Lecture 10. Recursion

Java Coding 3. Over & over again!

CSE 8A Lecture 21. SMarx extra final exam office hours Fri 3/15 11:15am-1pm EBU-3B #2206

Topic 23 arrays - part 3 (tallying, text processing)

Conditionals, Loops, and Style

EECS1710. Checklist from last lecture (Sept 9, 2014) " get an EECS account (if you don t have it already) " read sections

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

AP Computer Science Unit 1. Programs

Array Basics: Outline

Fundamentals of Object Oriented Programming

Object-Oriented Programming

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

Lecture 5: Methods CS2301

Topic 27 classes and objects, state and behavior

Transcription:

Topic 6 loops, figures, constants "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 our desire for elegant solutions, which 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 bu Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/

clicker question What is the base 10 equivalent of the base 2 number 1011001 A.27 B.89 C.93 D.127 E.1011001

What does 5! equal? A. 5 B. 10 C. 32 D. 120 E. a lot clicker question

clicker question Which of the following is closest to the value that overflows the Java int data type when calculating N! A. 1 B. 15 C. 60 D. 100 E. 1000

Drawing complex figures Use nested for loops to produce the following output. Why draw ASCII art? Real graphics require more finesse ASCII art has complex patterns Can focus on the algorithms #================# <>...<> <>...<> <>...<> <>...<> #================#

Development strategy Recommendations for managing complexity: 1. Design the program (think about steps or methods needed). write an English description of steps required use this description to decide the methods 2. Create a table for patterns of characters use tables to write your for loops #================# <>...<> <>...<> <>...<> <>...<> #================#

1. Pseudo-code pseudo-code: An English description of an algorithm. Example: Drawing a 12 wide by 7 tall box of stars print 12 stars. for (each of 5 lines) { print a star. print 10 spaces. print a star. print 12 stars. ************ * * * * * * * * * * ************

Pseudo-code algorithm 1. Line #, 16 =, # 2. Top half spaces (decreasing) <> dots (increasing) <> spaces (same as above) 3. Bottom half (top half upside-down) 4. Line #, 16 =, # #================# <>...<> <>...<> <>...<> <>...<> #================#

Methods from pseudocode public class Mirror { public static void main(string[] args) { line(); tophalf(); bottomhalf(); line(); public static void tophalf() { for (int line = 1; line <= 4; line++) { // contents of each line public static void bottomhalf() { for (int line = 1; line <= 4; line++) { // contents of each line public static void line() { //...

2. Tables A table for the top half: Compute spaces and dots expressions from line number line spaces -2 * line + 8 dots 4 * line - 4 1 6 6 0 0 2 4 4 4 4 3 2 2 8 8 4 0 0 12 12 #================# <>...<> <>...<> <>...<> <>...<> #================#

3. Writing the code Useful questions about the top half: What methods? (think structure and redundancy) Number of (nested) loops per line? #================# <>...<> <>...<> <>...<> <>...<> #================#

Partial solution // Prints the expanding pattern of <> for // the top half of the figure. public static void tophalf() { for (int line = 1; line <= 4; line++) { System.out.print(" "); for (int space = 1; space <= (line * -2 + 8); space++) { System.out.print(" "); System.out.print("<>"); for (int dot = 1; dot <= (line * 4-4); dot++) { System.out.print("."); System.out.print("<>"); for (int space = 1; space <= (line * -2 + 8); space++) { System.out.print(" "); System.out.println(" ");

Class constants and scope reading: 2.4

Scaling the mirror Modify the Mirror program so that it can scale. The current mirror (left) is at size 4; the right is at size 3. We'd like to structure the code so we can scale the figure by changing the code in just one place. #================# <>...<> <>...<> <>...<> <>...<> #================# #============# <>...<> <>...<> #============#

Limitations of variables Idea: Make a variable to represent the size. Use the variable's value in the methods. Problem: A variable in one method can't be seen in others. public static void main(string[] args) { int size = 4; tophalf(); printbottom(); public static void tophalf() { for (int i = 1; i <= size; i++) { // ERROR: size not found... public static void bottomhalf() { for (int i = size; i >= 1; i--) { // ERROR: size not found...

i's scope Scope scope: The part of a program where a variable exists. From its declaration to the end of the { braces A variable declared in a for loop exists only in that loop. A variable declared in a method exists only in that method. public static void example() { int x = 3; x's scope for (int i = 1; i <= 10; i++) { System.out.println(x); // i no longer exists here // x ceases to exist here

Scope implications Variables whose scope does NOT overlap can have same name. for (int i = 1; i <= 100; i++) { System.out.print("/"); for (int i = 1; i <= 100; i++) { System.out.print("\\"); int i = 5; // OK // OK: outside of loop's scope A variable can't be declared twice or used out of its scope. for (int i = 1; i <= 100 * line; i++) { int i = 2; // ERROR: overlapping scope System.out.print("/"); i = 4; // ERROR: outside scope

Class constants class constant: A fixed value visible to the whole program. value can be set only at declaration; cannot be reassigned, hence the name: constant Syntax: public static final <type> <name> = <exp>; name in ALL_UPPER_CASE by convention Examples: public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE = 0.5; public static final int SSN = 658234569;

Constants and figures Consider the task of drawing the following scalable figure: +/\/\/\/\/\/\/\/\/\/\+ Multiples of 5 occur many times +/\/\/\/\/\/\/\/\/\/\+ +/\/\/\/\+ The same figure at size 2 +/\/\/\/\+

Repetitive figure code public class Sign { public static void main(string[] args) { drawline(); drawbody(); drawline(); public static void drawline() { System.out.print("+"); for (int i = 1; i <= 10; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawbody() { for (int line = 1; line <= 5; line++) { System.out.print(" "); for (int spaces = 1; spaces <= 20; spaces++) { System.out.print(" "); System.out.println(" ");

Adding a constant public class Sign { public static final int HEIGHT = 5; public static void main(string[] args) { drawline(); drawbody(); drawline(); public static void drawline() { System.out.print("+"); for (int i = 1; i <= HEIGHT * 2; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawbody() { for (int line = 1; line <= HEIGHT; line++) { System.out.print(" "); for (int spaces = 1; spaces <= HEIGHT * 4; spaces++) { System.out.print(" "); System.out.println(" ");

Complex figure w/ constant Modify the Mirror code to be resizable using a constant. A mirror of size 4: #================# <>...<> <>...<> <>...<> <>...<> #================# A mirror of size 3: #============# <>...<> <>...<> #============#

Clicker Question Should every instance of the literal int 4 and multiples of 4 in the program be replaced with the class constant SIZE? A. Yes B. No

Using a constant Constant allows many methods to refer to same value: public static final int SIZE = 4; public static void main(string[] args) { tophalf(); printbottom(); public static void tophalf() { for (int i = 1; i <= SIZE; i++) {... public static void bottomhalf() { for (int i = SIZE; i >= 1; i--) {... // OK // OK

Loop tables and constant Let's modify our loop table to use SIZE This can change the amount added in the loop expression SIZE line spaces -2*line + (2*SIZE) dots 4*line - 4 4 1,2,3,4 6,4,2,0-2*line + 8 0,4,8,12 4*line - 4 3 1,2,3 4,2,0-2*line + 6 0,4,8 4*line - 4 #================# #============# <>...<> <>...<> <>...<> <>...<> <>...<> <>...<> #============# #================#

Partial solution public static final int SIZE = 4; // Prints the expanding pattern of <> for the top half of the figure. public static void tophalf() { for (int line = 1; line <= SIZE; line++) { System.out.print(" "); { { for (int space = 1; space <= (line * -2 + (2*SIZE)); space++) System.out.print(" "); System.out.print("<>"); for (int dot = 1; dot <= (line * 4-4); dot++) { System.out.print("."); System.out.print("<>"); for (int space = 1; space <= (line * -2 + (2*SIZE)); space++) System.out.print(" "); System.out.println(" ");

Observations about constant The constant can change the "intercept" in an expression. Usually the "slope" is unchanged. public static final int SIZE = 4; for (int space = 1; space <= (line * -2 + (2 * SIZE)); space++) { System.out.print(" "); It doesn't replace every occurrence of the original value. for (int dot = 1; dot <= (line * 4-4); dot++) { System.out.print(".");

Another Example Create a program to produce the following ASCII art rocket SIZE = 3 for the rocket to the right

SIZE = 4 Rocket

SIZE = 5 Rocket

Assignment 2: ASCII Art ##### ##### ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ -O-O-O- ~~~~~~~~~ /"'"'"'"'"'"'"'"'"'"\ /"'"'"'"'"'"'"'"'"'"'"'"'"\ /"O"O"O"O"O"O"O"O"O"O"O"O"\ /"O"O"O"O"O"O"O"O"O"O"O"O"\ /"O"O"O"O"O"O"O"O"O"O"O"O"\