Recap: Assignment as an Operator CS 112 Introduction to Programming

Similar documents
CS 112 Introduction to Programming

Building Java Programs

Building Java Programs

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

Topic 5 for loops and nested loops

CS 112 Introduction to Programming

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

Building Java Programs

CS 112 Introduction to Programming

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

Building Java Programs

Repetition with for loops

Introduction to Computer Programming

Primitive data, expressions, and variables

CS 112 Introduction to Programming

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

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

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

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

Lecture 13: Two- Dimensional Arrays

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Topic 6 loops, figures, constants

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS 112 Introduction to Programming

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

Topic 6 Nested for Loops

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

CS 112 Introduction to Programming. (Spring 2012)

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

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

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Top-Down Program Development

CS 112 Introduction to Programming. Final Review. Topic: Static/Instance Methods/Variables: I am confused

CS111: PROGRAMMING LANGUAGE II

CIS 110: Introduction to Computer Programming

Chapter 4: Control structures. Repetition

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

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

Introduction to Java & Fundamental Data Types

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

CS1150 Principles of Computer Science Loops (Part II)

Chapter 4: Control structures

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 Spring 2016 Howard Rosenthal

CS 112 Introduction to Programming

Repetition CSC 121 Fall 2014 Howard Rosenthal

ECE 122. Engineering Problem Solving with Java

Warmup : Name that tune!

Introduction to the Java Basics: Control Flow Statements

CS 112 Introduction to Programming. (Spring 2012)

Iteration statements - Loops

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CSc 110, Spring 2017 Lecture 3: Expressions, Variables and Loops. Adapted from slides by Marty Stepp and Stuart Reges

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

CT 229 Java Syntax Continued

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

CS111: PROGRAMMING LANGUAGE II

Chapter 7. Iteration. 7.1 Multiple assignment

Lecture 5: Methods CS2301

Fundamentals of Programming Session 13

More on control structures

Repetition, Looping CS101

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

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

Example: Monte Carlo Simulation 1

CS110D: PROGRAMMING LANGUAGE I

LEC03: Decisions and Iterations

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

Object-Oriented Programming

Loops / Repetition Statements

Instructor: Eng.Omar Al-Nahal

Bjarne Stroustrup. creator of C++

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Topic 4 Expressions and variables

Basics of Java Programming

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Lecture 6: While Loops and the Math Class

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

1 Lexical Considerations

Research Group. 2: More types, Methods, Conditionals

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

Iterative Languages. Scoping

Computer Science is...

Unit 1 Lesson 4. Introduction to Control Statements

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

Last Class. While loops Infinite loops Loop counters Iterations

Course Outline. Introduction to java

LECTURE 5 Control Structures Part 2

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

Repetition, Looping. While Loop

Transcription:

Recap: Assignment as an Operator CS 112 Introduction to Programming q You can consider assignment as an operator, with a (Spring 2012) lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated Lecture #7: Variable Scope, Constants, and Loops answer = sum / 4 + MAX * lowest; 4 Zhong Shao Department of Computer Science Yale University Office: 314 Watson 1 3 2 Then the result is stored in the variable on the left hand side, overwritten previous value http://flint.cs.yale.edu/cs112 Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the two textbooks: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne and Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Repetition with for Loops for loop syntax for (initialization; test; update) {... q Java's for loop statement performs a task many times. preheatoven(); mixbatter(); for (int i = 1; i <= 4; i++) { bake(); // repeat 4 times header body decorate(); preheatoven(); mixbatter(); bake(); bake(); bake(); bake(); dcorate(); Perform initialization once. Repeat the following: Check if the test is true. If not, stop. Execute the statements. Perform the update. 1

The for Statement: Syntax Flowchart of a for loop for ( initialization ; condition ; increment ) Reserved word The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false initialization for ( initialization ; condition ; increment ) condition evaluated Both semi-colons are always required true statement false The increment portion is executed at the end of each iteration increment Initialization Test for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); q Tells Java what variable to use in the loop The variable is called a loop counter can use any name, not just i can start at any value, not just 1 only valid in the loop Performed once as the loop begins q Tests the loop counter variable against a limit Uses comparison operators: < less than <= less than or equal to > greater than >= greater than or equal to 2

Update Increment and decrement for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); q Typically changes the loop counter variable shortcuts to increase or decrease a variable's value by 1 Shorthand Equivalent longer version variable++; variable = variable + 1; variable--; variable = variable - 1; int x = 2; x++; // x = x + 1; // x now stores 3 double gpa = 2.5; gpa--; // gpa = gpa - 1; // gpa now stores 1.5 Modify-and-assign operators Simplification shortcuts to modify a variable's value Shorthand Equivalent longer version variable += value; variable = variable + value; variable -= value; variable = variable - value; variable *= value; variable = variable * value; variable /= value; variable = variable / value; variable %= value; variable = variable % value; q Since such update expressions are so common: count = count + increment; count += increment; x += 3; // x = x + 3; gpa -= 0.5; // gpa = gpa - 0.5; number *= 2; // number = number * 2; count ++; when increment is 1 3

More Assignment-related Operators Example: Repetition over a range q Increment and decrement operators: ++, -- q Assignment operators: +=, -=, *=, /= these three expressions have the same effect count = count + 1; count += 1; count ++; System.out.println("1 squared = " + 1 * 1); System.out.println("2 squared = " + 2 * 2); System.out.println("3 squared = " + 3 * 3); System.out.println("4 squared = " + 4 * 4); System.out.println("5 squared = " + 5 * 5); System.out.println("6 squared = " + 6 * 6); Intuition: "I want to print a line for each number from 1 to 6" these two expressions have the same effect count = count - 10; count -= 10; Example: Repetition over a range Loop Walkthrough 1 2 3 System.out.println("1 squared = " + 1 * 1); System.out.println("2 squared = " + 2 * 2); System.out.println("3 squared = " + 3 * 3); System.out.println("4 squared = " + 4 * 4); System.out.println("5 squared = " + 5 * 5); System.out.println("6 squared = " + 6 * 6); Intuition: "I want to print a line for each number from 1 to 6" q The for loop does exactly that! for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); "For each integer i from 1 through 6, print..." 5 4 for (int i = 1; i <= 4; i++) { System.out.println(i + " squared = " + (i * i)); System.out.println("Whoo!"); Output: 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 Whoo! 1 5 2 3 4 4

Multi-line Loop Body Counting Down System.out.println("+----+"); for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\"); System.out.println("+----+"); Output: +----+ \ / / \ \ / / \ \ / / \ +----+ q There is much flexibility in initialization and update: instead of increasing the loop counter, you can decrease it for (initialization; test; update) {... set a large value check if reach lower bound reduce q Exercise: write a program generating output T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! Counting Down Counting Down: Exercise q The update uses -- to make the loop count down. The test must say > instead of < for (int i = 10; i >= 1; i--) { System.out.print(i + ", "); q Revise the program so that you have to increase the counter i from 1 to 10 but still produce the same output: T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! for (int i = 1; i <= 10; i++) { //??? 5

Counting Down: Revision Counting Down: Revision q The code has the magic number 11, whose relationship with 10 is not represented: for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); q If I want to count down from 12, what should I change? T-minus 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! Change to 12? for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); relation? 21 Counting Down: Revision Counting Down: Revision q Redundant specification: for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); int N = 10; for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); 6

Constants Constant q A constant variable is an identifier that is similar to a variable except that it holds one value for its entire existence why constants? q In Java, we use the final modifier to declare a variable constant, and the convention is to use all capital words to name a constant, e.g., final int MONTHES_PER_YEAR = 12; q The compiler will issue an error if you try to change the value of a constant variable after it is set q Use keywords to tell computer your intention q If there is a final before a variable declaration, it is your promise to the computer that you will not modify it after declaration q If you break your promise, the compiler will catch you CPSC112 Constant Variable Scope final int N = 10; for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); i's scope q 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; for (int i = 1; i <= 10; i++) { System.out.println(x); // // end of example 7

Why Scope? Scope Implications 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 public static void amethod() { int x = 1; public static void bmethod() { int x = 2; q Variables without overlapping scope can have same name: public static void Countdown2() { for (int i = 1; i <= 10; i++) { System.out.print( 11-i ); System.out.println( Count down again ); for (int i = 1; i <= 10; i++) { System.out.print(11 - i); int i = 5; Scope Implications Class Scope q In a method, 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 public class CountDown { static int i; public static void main(string[] args) { for (i = 1; i <= 10; i++) { System.out.println( 11 i ); System.out.println( Final count: + i); // end of main // end of class 8

Code Beauty Contest : Which One s Better? public class CountDown { static int N = 10; public static void main(string[] args) { for (i = 1; i <= N; i++) { System.out.println( N+1 i +, ); // end of main // end of class public static void main(string[] args) { int N = 10; for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); Code Beauty Contest: Which One s Better? int N = 10; for (int i = N; i >= 1; i--) { System.out.print(i +, ); int N = 10; for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); Nested Loops Nested for loop exercise q Nested loop: A loop placed inside another loop. q Output: for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); // to end the line ********** ********** ********** ********** ********** 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("*"); q The outer loop repeats 5 times; the inner one 10 times. "sets and reps" exercise analogy 9

Nested for loop exercise Nested for loop exercise 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("*"); 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: * ** *** **** ***** Nested for loop exercise Nested for loop exercise 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 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 ); q Output: 1 22 333 4444 55555 10

Common Errors Complex lines q Both of the following sets of code produce infinite loops: for (int i = 1; i <= 5; i++) { for (int j = 1; i <= 10; j++) { System.out.print("*"); for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; i++) { System.out.print("*"); q What nested for loops produce the following output? inner loop (repeated characters on each line)...2..3.4 5 outer loop (loops 5 times because there are 5 lines) q We must build multiple complex lines of output using: an outer "vertical" loop for each of the lines inner "horizontal" loop(s) for the patterns within each line Outer and inner loop Nested for loop exercise q First write the outer loop, from 1 to the number of lines. for (int line = 1; line <= 5; line++) {... q Now look at the line contents. Each line has a pattern: some dots (0 dots on the last line), then a number...2..3.4 5 q Make a table to represent any patterns on each line....2..3.4 5 line # of dots 1 4 2 3 3 2 4 1 5 0-1 * line + 5 4 3 2 1 0 Observation: the number of dots is related to the line number. 11

Nested for loop solution Place Introducing Inconsistency? q Answer: for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1 * line + 5); j++) { System.out.println(line); for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1 * line + 5); j++){ System.out.println(line); q Output:...2..3.4 5 Fixing for Consistency Nested for loop exercise int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { System.out.println(line); q What is the output of the following nested for loops? int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { for (int k = 1; k <= line; k++) { System.out.print(line); q Answer:...22..333.4444 55555 12

Nested for loop exercise Nested for loop exercise q Modify the code below to produce this output:...2...3...4... 5... int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { for (int k = 1; k <= line; k++) { System.out.print(line); q Modify the previous code to produce this output:...2...3...4... 5... q Answer: int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { System.out.print(line); for (int j = 1; j <= (line - 1); j++) { Reuse the Code Recap: Variable Scope q Printing a diagonal matrix is a useful task:...2...3...4... 5... q How do we reuse the code for different N? int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { System.out.print(line); for (int j = 1; j <= (line - 1); j++) { q Two types of variables Class variables: declared inside a class but not any method class variable s scope is the whole class cover more later in the course Local variables: declared in a method of a class a local variable starts to exist at the point it is declared and disappears at the end of enclosing block we say that the variable is in scope in this range if a local variable x is in scope, you can use x directly in any statement, e.g., if integer x is in scope, you can write System.out.println ( x ); 13

Local Variable Scoping Rule thismethodname() { // block 1 int x = 2; // x is in scope until end of block 1 { // block 2 // x is also in scope in the nested block int y = 3; // now y in scope until end of block 2 // int x = 4; // is this OK? // end of block 2 // end of block 1 14