Primitive data, expressions, and variables

Similar documents
Building Java Programs

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

Repetition with for loops

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Topic 6 Nested for Loops

Building Java Programs

Building Java Programs

Topic 4 Expressions and variables

Building Java Programs

Topic 5 for loops and nested loops

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

Building Java Programs

Building Java Programs

CSE 142, Summer 2015

CSE 142, Summer 2014

CS 112 Introduction to Programming

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

Building Java Programs

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

Recap: Assignment as an Operator CS 112 Introduction to Programming

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

Topic 6 loops, figures, constants

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

Lecture 2: Operations and Data Types

Introduction to Computer Programming

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Basics of Java Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Introduction to Computer Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Object-Oriented Programming

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Operators. Java operators are classified into three categories:

Full file at

Course Outline. Introduction to java

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Chapter 3: Operators, Expressions and Type Conversion

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Declaration and Memory

Basic Operations jgrasp debugger Writing Programs & Checkstyle

DATA TYPES AND EXPRESSIONS

CS 106 Introduction to Computer Science I

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

Add Subtract Multiply Divide

Lecture Set 4: More About Methods and More About Operators

COMP Primitive and Class Types. Yi Hong May 14, 2015

Chapter 7. Iteration. 7.1 Multiple assignment

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Introduction to Java & Fundamental Data Types

COMP 202 Java in one week

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

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Midterms Save the Dates!

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

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

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

CIS 110: Introduction to Computer Programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Program Fundamentals

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

CS 112 Introduction to Programming

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Object Oriented Software Design

UNIT- 3 Introduction to C++

CEN 414 Java Programming

4 Programming Fundamentals. Introduction to Programming 1 1

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

COMP-202 Unit 4: Programming with Iterations

The C++ Language. Arizona State University 1

CS111: PROGRAMMING LANGUAGE II

Algorithms and Programming I. Lecture#12 Spring 2015

Elementary Programming

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

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Control Structures in Java if-else and switch

JAVA OPERATORS GENERAL

CMPT 125: Lecture 3 Data and Expressions

Chapter 4: Control structures. Repetition

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Unit 3. Operators. School of Science and Technology INTRODUCTION

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Object Oriented Programming with Java

Transcription:

How the computer sees the world Primitive data, expressions, and variables Readings:.. Internally, the computer stores everything in terms of s and 0 s Example: h 0000 "hi" 0000000 0 0000 How can the computer tell the difference between an h and 0? Data types Primitive types data type: A category of data values. Example: integer, real number, string Data types are divided into two classes: primitive types: Java's built-in simple data types for numbers, text characters, and logic. object types: Coming soon! Java has eight primitive types. We will cover two for now. Name Description Examples int integers, -, 0, 969 double real numbers., -., 9.e Numbers with a decimal point are treated as real numbers. Question: Isn t every integer a real number? Why bother? Integer or real number? Manipulating data via expressions Which category is more appropriate? integer (int). Temperature in degrees Celsius. The population of lemmings. Your grade point average. A person's age in years. A person's weight in pounds 6. A person's height in meters real number (double) 7. Number of miles traveled 8. Number of dry days in the past month 9. Your locker number 0. Number of seconds left in a game. The sum of a group of integers. The average of a group of integers credit: Kate Deibel, http://www.cs.washington.edu/homes/deibel/cats/ expression: A data value or a set of operations that produces a value. Examples: + * "CSE" ( + ) % * 6

The operators Evaluating expressions Arithmetic operators we will use: + addition - subtraction or negation * multiplication / division % modulus, a.k.a. remainder When Java executes a program and encounters an expression, the expression is evaluated (i.e., computed). Example: * evaluates to System.out.println( * ) prints (after evaluating * ) How could we print the text * on the console? 7 8 Evaluating expressions: Integer division Evaluating expressions: The modulus (%) When dividing integers, the result is also an integer: the quotient. Example: / evaluates to, not. (truncate the number) ) 7 ) 7 Examples: / 7 is / is 7 8 / 0 is 8 6 / 00 is / 0 is illegal 9 The modulus computes the remainder from a division of integers. Example: % is % 7 is ) 7 ) 7 What are the results of the following expressions? % 6 % 8 % 0 % 0 0 Applying the modulus Applying the modulus What expression obtains the last digit (unit s place) of a number? Example: From 087, obtain the 7. the last digits of a Social Security Number? Example: From 68689, obtain 689. How can we use the % operator to determine whether a number is odd? How about if a number is divisible by, say, 7? the second-to-last digit (ten s place) of a number? Example: From 7, obtain the.

Precedence: Remember PEMDAS? Precedence examples precedence: Order in which operations are computed in an expression. Operators on the same level are evaluated from left to right. Example: - + is (not -) Spacing does not affect order of evaluation. Example: + * - is Parentheses Multiplication, Division, Mod Addition, Subtraction () * / % + - * + * / \_/ + * / \_/ + / \ / + \ / + / * - \_/ + 0 * - \ / + 0 - \ / - \ / - Precedence exercise Real numbers (double) Evaluate the following expressions: 9 / 69 % 0 7 + 6 * 7 * 6 + 8 % 00 / 6 * - 9 / (- 7) * 6 + (8 % (7 - )) Which parentheses are unnecessary? The operators also work with real numbers. The division operator produces an exact answer. Examples:.0 /.0 is 7.. +. is 7.8. +.0 *.0 is. The same precedence rules apply. 6 Real numbers example Precision in real numbers.0 *. +. *.0 /.0 \ /.8 +. *.0 /.0 \ /.8 + 9.0 /.0 \ /.8 +. \ / 9. The computer internally represents real numbers in an imprecise way. Example: System.out.println(0. + 0.); The output is 0.000000000000000! 7 8

Mixing integers and real numbers Mixed types example When an operator is used on an integer and a real number, the result is a real number. Examples:. * is.6 /.0 is 0. The conversion occurs on a per-operator basis. It affects only its two operands. 7 / *. + / \_/ *. + / \ /. + / \_/. + \ /. Notice how / is still above, not.. 9.0 + 0 / *. - 6 / \ /.0 + *. - 6 / \ /.0 + 7. - 6 / \_/.0 + 7. - \ / 9. - \ / 8. 0 Concatenation: Operating on strings String expressions string concatenation: Using the + operator between a string and another value to make a longer string. Examples: "hello" + is "hello" + "abc" + is "abc" "abc" + + is "abc" + + "abc" is "abc" "abc" + 9 * is "abc7" (what happened here?) "" + is "" - + "abc" is "abc" Lets us print more complicated messages with computed values. System.out.println("Your grade was " + ((9. + 7.9 + 8.6) /.0)); System.out.println("There are " + ( + 7 + + 9 + ) + " students in the course."); "abc" + - causes a compiler error. Why? What was the answer again? What was the answer again? Using the data from the last slide, what if we wanted to print the following? Your grade was 8. Summary: Course grade: 8. Answer? System.out.println("Your grade was " + ((9. + 7.9 + 8.6) /.0)); System.out.println("Summary:"); System.out.println("Course grade: " + ((9. + 7.9 + 8.6) /.0)); Evaluating expressions are somewhat like using the computer as a calculator. A good calculator has "memory" keys to store and retrieve a computed value.

Variables Declaring variables variable: A piece of your computer's memory that is given a name and type and can store a value. Usage: compute an expression's result store that result into a variable use that variable later in the program Variables are a bit like preset stations on a car stereo: To create a variable, it must be declared. Variable declaration syntax: <type> <name>; Convention: Variable identifiers follow the same rules as method names. Examples: double mygpa; int varname; 6 Declaring variables Setting variables Declaring a variable sets aside a piece of memory in which you can store a value. int y; Inside the computer: x:? y:? assignment statement: A Java statement that stores a value into a variable. Variables must be declared before they can be assigned a value. Assignment statement syntax: <variable> = <expression>; Examples: x = * ; x: 8 mygpa:. mygpa =.; (The memory still has no value yet.) 7 8 Setting variables Using variables A variable can be assigned a value more than once. Example: x = ; System.out.println(x); // x = + 7; System.out.println(x); // 9 Once a variable has been assigned a value, it can be used in any expression. x = * ; System.out.println(x * - ); The above has output equivalent to: System.out.println(8 * - ); What happens when a variable is used on both sides of an assignment statement? x = ; x = x + ; // what happens? 0

Errors in coding Assignment vs. algebra ERROR: Declaring two variables with the same name Example: // ERROR: x already exists ERROR: Reading a variable s value before it has been assigned Example: System.out.println(x); // ERROR: x has no value The assignment statement is not an algebraic equation! <variable> = <expression>; means: "store the value of <expression> into <variable>" Some people read x = * ; as "x gets the value of * " ERROR: = + ; is an illegal statement, because is not a variable. Assignment and types Assignment exercise A variable can only store a value of its own type. Example: x =.; // ERROR: x can only store int An int value can be stored in a double variable. Why? The value is converted into the equivalent real number. Example: double mygpa; mygpa:.0 mygpa = ; What is the output of the following Java code? x = ; int y; y = x; x = ; System.out.println(x); System.out.println(y); Assignment exercise Shortcut: Declaring and initializing What is the output of the following Java code? int number; number = + * ; System.out.println(number- ); number = 6 % 6; System.out.println( * number); What is the output of the following Java code? double average; average = ( + 8) / ; System.out.println(average); average = ( + average * ) / ; System.out.println(average); A variable can be declared and assigned an initial value in the same statement. Declaration/initialization statement syntax: <type> <name> = <expression>; Examples: double mygpa =.9; int x = ( % ) + ; 6 6

Shortcut: Declaring many variables at once Shortcut: Modify and assign It is legal to declare multiple variables on one line: <type> <name>, <name>,..., <name>; Examples: int a, b, c; double x, y; It is also legal to declare/initialize several at once: <type> <name> = <expression>,..., <name> = <expression>; Examples: int a =, b =, c = -; double grade =., delta = 0.; NB: The variables must be of the same type. Java has several shortcut operators that allow you to quickly modify a variable's value. Shorthand <variable> += <exp>; <variable> -= <exp>; <variable> *= <exp>; <variable> /= <exp>; <variable> %= <exp>; Examples: Equivalent longer version <variable> = <variable> + (<exp>); <variable> = <variable> - (<exp>); <variable> = <variable> * (<exp>); <variable> = <variable> / (<exp>); <variable> = <variable> % (<exp>); x += - ; // x = x + (- ); gpa- = 0.; // gpa = gpa (0.); number *= ; // number = number * (); 7 8 Shortcut: Increment and decrement Putting it all together: Exercise Incrementing and decrementing is used often enough that they have a special shortcut operator! Shorthand Equivalent longer version <variable>++; <variable> = <variable> + ; <variable>--; <variable> = <variable> - ; Examples: int x = ; x++; // x = x + ; // x now stores double gpa =.; gpa++; // gpa = gpa + ; // gpa now stores. 9 Write a program that stores the following data: Section AA has 7 students. Section AB has 8 students. Section AC has students. Section AD has students. Section AE has students. Section AF has 7 students. The average number of students per section. Have your program print the following: There are students in Section AE. There are an average of students per section. 0 The for loop and scope Readings:.. Repetition How can we eliminate this redundancy? 7

Looping via the for loop The for loop is NOT a method for loop: A block of Java code that executes a group of statements repeatedly until a given test fails. General syntax: for (<initialization>; <test>; <update>) { <statement>; <statement>;... <statement>; The for loop is a control structure a syntactic structure that controls the execution of other statements. Example: Shampoo hair. Rinse. Repeat. Example: for (int i = ; i <= 0; i++) { System.out.println("I will not throw..."); for loop over range of ints for loop flow diagram We'll write for loops over integers in a given range. The <initialization> declares a loop counter variable that is used in the test, update, and body of the loop. for (int <name> = ; <name> <= <value>; <name>++) { for (<init>; <test>; <update>) { <statement>; <statement>;... <statement>; Example: for (int i = ; i <= ; i++) { System.out.println(i + " squared is " + (i * i)); "For each int i from through,... squared is squared is squared is 9 squared is 6 6 Loop walkthrough Loop example Code: for (int i = ; i <= ; i++) { System.out.println(i + " squared is " + (i * i)); squared is squared is squared is 9 i: Code: System.out.println("+----+"); for (int i = ; i <= ; i++) { System.out.println("\\ /"); System.out.println("/ \\"); System.out.println("+----+"); +----+ \ / / \ \ / / \ \ / / \ +----+ 7 8 8

Varying the for loop Varying the for loop The initial and final values for the loop counter variable can be arbitrary expressions: Example: for (int i = -; i <= ; i++) { System.out.println(i); - - - 0 Example: for (int i = + * ; i <= 8 % 00; i++) { System.out.println(i + " squared is " + (i * i)); The update can be a -- (or any other operator). Caution: This requires changing the test from <= to >=. System.out.print("T-minus"); for (int i = ; i >= ; i--) { System.out.println(i); System.out.println("Blastoff!"); T-minus Blastoff! 9 0 Aside: System.out.print Errors in coding What if we wanted the output to be the following? T-minus Blastoff! System.out.print prints the given output without moving to the next line. System.out.print("T-minus "); for (int i = ; i >= ; i--) { System.out.print(i + " "); System.out.println("Blastoff!"); When controlling a single statement, the { braces are optional. for (int i = ; i <= 6; i++) System.out.println(i + " squared is " + (i * i)); This can lead to errors if a line is not properly indented. for (int i = ; i <= ; i++) System.out.println("This is printed times"); System.out.println("So is this... or is it?"); This is printed times This is printed times This is printed times So is this... or is it? Moral: Always use curly braces and always use proper indentation. Errors in coding for loop exercises ERROR: Loops that never execute. for (int i = 0; i < ; i++) { System.out.println("How many times do I print?"); ERROR: Loop tests that never fail. A loop that never terminates is called an infinite loop. for (int i = 0; i >= ; i++) { System.out.println("Runaway Java program!!!"); Write a loop that produces the following output. On day # of Christmas, my true love sent to me On day # of Christmas, my true love sent to me On day # of Christmas, my true love sent to me On day # of Christmas, my true love sent to me On day # of Christmas, my true love sent to me... On day # of Christmas, my true love sent to me Write a loop that produces the following output. 6 8 Who do we appreciate 9

Scope Scope: for loop scope: The portion of a program where a given variable exists. A variable's scope is from its declaration to the end of the { braces in which it was declared. public class ScopeExample { public static void main(string[] args) { int x = ; int y = 7; computesum(); System.out.println("sum = " + sum); // illegal: sum is out of scope public static void computesum() { int sum = x + y; // illegal: x and y are out of scope Why not just have the scope of a variable be the whole program? Special case: If a variable is declared in the <initialization> part of a for loop, its scope is the for loop. public static void example() { int x = ; for (int i = ; i <= 0; i++) { System.out.println(x); // i no longer exists here // x ceases to exist here i's scope x's scope 6 Errors in coding Errors in coding ERROR: Using a variable outside of its scope. ERROR: Declaring variables with the same name with overlapping scope. public static void main(string[] args) { example(); System.out.println(x); // illegal for (int i = ; i <= 0; i++) { int y = ; System.out.println(y); System.out.println(y); // illegal public static void example() { int x = ; System.out.println(x); public static void main(string[] args) { int x = ; for (int i = ; i <= ; i++) { int y = ; System.out.println(y); for (int i = ; i <= ; i++) { int y = ; int x = ; // illegal System.out.println(y); public static void anothermethod() { int i = 6; int x = ; int y = ; System.out.println(i + ", " + x + ", " + y); 7 8 Mapping loops to numbers Mapping loops to numbers Suppose that we have the following loop: for (int count = ; count <= ; count++) {... What statement could we write in the body of the loop that would make the loop print the following output? 6 9 Answer: for (int count = ; count <= ; count++) { System.out.print( * count + " "); 9 Now consider another loop of the same style: for (int count = ; count <= ; count++) {... What statement could we write in the body of the loop that would make the loop print the following output? 7 0 6 Answer: for (int count = ; count <= ; count++) { System.out.print( * count + + " "); 60 0

Loop number tables Another perspective: Slope-intercept What statement could we write in the body of the loop that would make the loop print the following output? 7 7 count (x) number to print (y) To find the pattern, it can help to make a table. Each time count goes up by, the number should go up by. But count * is too big by, so we must subtract. count number to print count * count * - 7 0 7 7 0 7 6 0 0 7 0-0 6-7 -0 6 Another perspective: Slope-intercept Another perspective: Slope-intercept Caution: This is algebra, not assignment! Recall: slope-intercept form (y = mx + b) Slope is defined as rise over run (i.e. rise / run). Since the run is always (we increment along x by ), we just need to look at the rise. The rise is the difference between the y values. Thus, the slope (m) is the difference between y values; in this case, it is +. To compute the y-intercept (b), plug in the value of y at x = and solve for b. In this case, y =. y = m * x + b = * + b Then b = - So the equation is y = m * x + b y = * x y = * count - count (x) number to print (y) 7 7 Algebraically, if we always take the value of y at x =, then we can solve for b as follows: y = m * x + b y = m * + b y = m + b b = y m In other words, to get the y-intercept, just subtract the slope from the first y value (b = = -) This gets us the equation y = m * x + b y = * x y = * count (which is exactly the equation from the previous slides) 6 6 Loop table exercise Nested for loops What statement could we write in the body of the loop that would make the loop print the following output? 7 9 Let's create the loop table together. Each time count goes up, the number should... But this multiple is off by a margin of... count number to print 7 9 count * - - -8 - -6-0 count * - + 7 9 6 nested loop: Loops placed inside one another. Caution: Make sure the inner loop's counter variable has a different name! for (int i = ; i <= ; i++) { System.out.println("i = " + i); for (int j = ; j <= ; j++) { System.out.println(" j = " + j); i = j = j = i = j = j = i = j = j = 66

Nested loops example Nested loops example Code: for (int i = ; i <= ; i++) { for (int j = ; j <= 0; j++) { System.out.print((i * j) + " "); // to end the line 6 7 8 9 0 6 8 0 6 8 0 6 9 8 7 0 8 6 0 8 6 0 0 0 0 0 0 Code: for (int i = ; i <= 6; i++) { for (int j = ; j <= 0; j++) { System.out.print("*"); ********** ********** ********** ********** ********** ********** 67 68 Nested loops example Nested loops example Code: for (int i = ; i <= 6; i++) { for (int j = ; j <= i; j++) { System.out.print("*"); * ** *** **** ***** ****** Code: for (int i = ; i <= 6; i++) { for (int j = ; j <= i; j++) { System.out.print(i); 666666 69 70 Nested loops example Nested loops Code: for (int i = ; i <= ; i++) { for (int j = ; j <= ( - i); j++) { System.out.print(" "); for (int k = ; k <= i; k++) { System.out.print(i); What nested for loops produce the following output? inner loop (repeated characters on each line)......... Key idea: outer loop (loops times because there are lines) outer "vertical" loop for each of the lines inner "horizontal" loop(s) for the patterns within each line 7 7

Nested loops Nested loops First, write the outer loop from to the number of lines desired. for (int line = ; line <= ; line++) {... Notice that each line has the following pattern: some number of dots (0 dots on the last line) a number......... Make a table:......... line # of dots line * - + 0 0 Answer: for (int line = ; line <= ; line++) { for (int j = ; j <= (line * - + ); j++) { System.out.print("."); System.out.println(line); value displayed 7 7 Errors in coding Commenting: for loops ERROR: Using the wrong loop counter variable. What is the output of the following piece of code? for (int i = ; i <= 0; i++) { for (int j = ; i <= ; j++) { System.out.print(j); What is the output of the following piece of code? for (int i = ; i <= 0; i++) { for (int j = ; j <= ; i++) { System.out.print(j); 7 Place a comment on complex loops explaining what they do from a conceptual standpoint, not the mechanics of the syntax. Bad: // This loop repeats 0 times, with i from to 0. for (int i = ; i <= 0; i++) { for (int j = ; j <= ; j++) { // loop goes times System.out.print(j); // print the j Better: // Prints ten times on ten separate lines. for (int i = ; i <= 0; i++) { for (int j = ; j <= ; j++) { System.out.print(j); // end the line of output 76 Managing complexity Drawing complex figures Write a program that produces the following figure as its output: Readings:.. #================# <><> <>...<> <>...<> <>...<> <>...<> <>...<> <>...<> <><> #================# Where do we even start?? 77 78

Drawing complex figures: Strategy Pseudo-code Write down some steps on paper before coding:. A pseudo-code description of the algorithm (in English). A table of each line's contents, to help see the pattern in the input pseudo-code: A written English description of an algorithm Example: Suppose we are trying to draw a box of stars which is characters wide and 7 tall. print stars. for each of lines, print a star. print 0 spaces. print a star. print stars. ************ * * * * * * * * * * ************ 79 80 Drawing complex figures: Pseudo-code Drawing complex figures: Tables A possible pseudo-code for our complex figure task:. Draw top line with #, 6 =, then #. Draw the top half with the following on each line: some spaces (possibly 0) <> some dots (possibly 0) <> more spaces (possibly 0). Draw the bottom half, which is the same as the top half but upside-down. Draw bottom line with #, 6 =, then # #================# <><> <>...<> <>...<> <>...<> <>...<> <>...<> <>...<> <><> #================# 8 A table of the lines in the "top half" of the figure: line spaces 6 0 line * - + 8 6 0 dots 0 8 line * - 0 8 #================# <><> <>...<> <>...<> <>...<> <>...<> <>...<> <>...<> <><> #================# 8 Drawing complex figures: Questions Partial solution How many loops do we need on each line of the top half of the output? Which loops are nested inside which other loops? // Prints the expanding pattern of <> for the top half of the figure. public static void drawtophalf() { for (int line = ; line <= ; line++) { System.out.print(""); for (int space = ; space <= (line * - + 8); space++) { System.out.print(" "); System.out.print("<>"); for (int dot = ; dot <= (line * - ); dot++) { System.out.print("."); System.out.print("<>"); How should we use static methods to represent the structure and redundancy of the output? for (int space = ; space <= (line * - + 8); space++) { System.out.print(" "); System.out.println(""); Question: Is there a pattern to the numbers? 8 8

Magic numbers Solution: Class constants Sometimes we have values (called magic numbers) that are used throughout the program. A normal variable cannot be used to fix the magic number problem. Why not? public static void main(string[] args) { int max = ; printtop(); printbottom(); public static void printtop() { for (int i = ; i <= max; i++) { for (int j = ; j <= i; j++) { System.out.print(j); // ERROR: max not found (out of scope) class constant: A variable that can be seen throughout the program. The value of a constant can only be set when it is declared. It cannot be changed while the program is running, hence the name: constant. public static void printbottom() { for (int i = max; i >= ; i--) { for (int j = i; j >= ; j--) { System.out.print(max); // ERROR: max not found (out of scope) // ERROR: max not found (out of scope) 8 86 Class constant: Syntax Class constant example Syntax: public static final <type> <name> = <value>; Class constants have to be declared outside the methods. Convention: Constant identifiers are written in uppercase separated by underscores. Examples: public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE =.; public static final int SSN = 6869; Class constants eliminates redundancy. public static final int MAX_VALUE = ; public static void main(string[] args) { printtop(); printbottom(); public static void printtop() { for (int i = ; i <= MAX_VALUE; i++) { for (int j = ; j <= i; j++) { System.out.print(j); public static void printbottom() { for (int i = MAX_VALUE; i >= ; i--) { for (int j = i; j >= ; j--) { System.out.print(MAX_VALUE); 87 88 Constants and figures Boo! Redundancy! Boo! Consider the task of drawing the following figures. +/\/\/\/\/\+ +/\/\/\/\/\+ +/\/\/\/\/\+ +/\/\/\/\/\+ How can a class constant help? Note the repetition of numbers based on in the code: public static void drawfigure() { drawplusline(); drawbarline(); drawplusline(); public static void drawplusline() { System.out.print("+"); for (int i = ; i <= ; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawbarline() { System.out.print(""); for (int i = ; i <= 0; i++) { System.out.print(" "); System.out.println(""); It would be cumbersome to resize the figure. +/\/\/\/\/\+ +/\/\/\/\/\+ 89 90

Class constants to the rescue! Drawing complex figures: Resizing A class constant will fix the "magic number" problem. public static final int FIGURE_WIDTH = ; public static void drawfigure() { drawplusline(); drawbarline(); drawplusline(); public static void drawplusline() { System.out.print("+"); for (int i = ; i <= FIGURE_WIDTH; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawbarline() { System.out.print(""); for (int i = ; i <= * FIGURE_WIDTH; i++) { System.out.print(" "); System.out.println(""); Modify the previous program to use a constant so that it can show figures of different sizes. The figure originally shown has a size of. #================# <><> <>...<> <>...<> <>...<> <>...<> <>...<> <>...<> <><> #================# A figure of size : #============# <><> <>...<> <>...<> <>...<> <>...<> <><> #============# 9 9 Partial solution Class constant trickiness public static final int SIZE = ; // Prints the expanding pattern of <> for the top half of the figure. public static void drawtophalf() { for (int line = ; line <= SIZE; line++) { System.out.print(""); for (int space = ; space <= (line * - + ( * SIZE)); space++) { System.out.print(" "); System.out.print("<>"); for (int dot = ; dot <= (line * - ); dot++) { System.out.print("."); System.out.print("<>"); for (int space = ; space <= (line * - + ( * SIZE)); space++) { System.out.print(" "); System.out.println(""); 9 Adding a constant often changes the amount that is added to a loop expression, but the multiplier (slope) is usually unchanged. public static final int SIZE = ; for (int space = ; space <= (line * - + ( * SIZE)); space++) { System.out.print(" "); Caution: A constant does NOT always replace every occurrence of the original value. for (int dot = ; dot <= (line * - ); dot++) { System.out.print("."); 9 Complex figure exercise Write a program that produces the following figure as its output. Use nested for loops and static methods where appropriate. ====+==== # # # # # # ====+==== # # # # # # ====+==== Add a constant so that the figure can be resized. 9 Assignment : Space Needle /\ /::::::\ /::::::::::::\ /::::::::::::::::::\ """""""""""""""""""""""" \_/\/\/\/\/\/\/\/\/\/\/\_/ \_/\/\/\/\/\/\/\/\/\_/ \_/\/\/\/\/\/\/\_/ \_/\/\/\/\/\_/ %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% %%%% /\ /::::::\ /::::::::::::\ /::::::::::::::::::\ """""""""""""""""""""""" 96 6