CS 112 Introduction to Programming

Similar documents
Recap: Assignment as an Operator 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

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

Building Java Programs Chapter 2

CS 112 Introduction to Programming

Repetition with for loops

Introduction to Computer Programming

Building Java Programs

Primitive data, expressions, and variables

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

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

CS 112 Introduction to Programming

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

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

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

CS 112 Introduction to Programming. (Spring 2012)

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:

Chapter 7. Iteration. 7.1 Multiple assignment

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

Introduction to Java & Fundamental Data Types

CS1150 Principles of Computer Science Loops (Part II)

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

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

CS 112 Introduction to Programming

ECE 122. Engineering Problem Solving with Java

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

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

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

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

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

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

CT 229 Java Syntax Continued

CS111: PROGRAMMING LANGUAGE II

Lecture 5: Methods CS2301

Fundamentals of Programming Session 13

More on control structures

Repetition, Looping CS101

Example: Monte Carlo Simulation 1

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

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.

LEC03: Decisions and Iterations

CS110D: PROGRAMMING LANGUAGE I

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

Basics of Java Programming

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

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

Topic 4 Expressions and variables

1 Lexical Considerations

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

Lecture 6: While Loops and the Math Class

Research Group. 2: More types, Methods, Conditionals

Unit 1 Lesson 4. Introduction to Control Statements

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

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

Computer Science is...

Last Class. While loops Infinite loops Loop counters Iterations

Iterative Languages. Scoping

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

Transcription:

CS 112 Introduction to Programming (Spring 2012) Lecture #7: Variable Scope, Constants, and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson 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

Recap: Assignment as an Operator q You can consider assignment as an operator, with a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side, overwritten previous value

Repetition with for Loops q Java's for loop statement performs a task many times. preheatoven(); mixbatter(); for (int i = 1; i <= 4; i++) { bake(); decorate(); // repeat 4 times preheatoven(); mixbatter(); bake(); bake(); bake(); bake(); dcorate();

for loop syntax for (initialization; test; update) { statement; statement;... statement; header body Perform initialization once. Repeat the following: Check if the test is true. If not, stop. Execute the statements. Perform the update.

The for Statement: Syntax Reserved word The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; Both semi-colons are always required The increment portion is executed at the end of each iteration

Flowchart of a for loop for ( initialization ; condition ; increment ) statement; initialization condition evaluated true false statement increment

Initialization 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

Test for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); 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

Update for (int i = 1; i <= 6; i++) { System.out.println("I am so smart"); q Typically changes the loop counter variable

Increment and decrement 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 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; x += 3; // x = x + 3; gpa -= 0.5; // gpa = gpa - 0.5; number *= 2; // number = number * 2;

Simplification q Since such update expressions are so common: count = count + increment; count += increment; when increment is 1 count ++;

More Assignment-related Operators q Increment and decrement operators: ++, -- q Assignment operators: +=, -=, *=, /= these three expressions have the same effect count = count + 1; count += 1; count ++; these two expressions have the same effect count = count - 10; count -= 10;

Example: Repetition over a range 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"

Example: Repetition over a range 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..."

Loop Walkthrough 1 2 3 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 2 3 4 5

Multi-line Loop Body System.out.println("+----+"); for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\"); System.out.println("+----+"); Output: +----+ \ / / \ \ / / \ \ / / \ +----+

Counting Down q There is much flexibility in initialization and update: instead of increasing the loop counter, you can decrease it for (initialization; test; update) { statement; statement;... statement; 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 q The update uses -- to make the loop count down. The test must say > instead of < System.out.print("T-minus "); for (int i = 10; i >= 1; i--) { System.out.print(i + ", "); System.out.println("blastoff!");

Counting Down: Exercise 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! System.out.print("T-minus "); for (int i = 1; i <= 10; i++) { //??? System.out.println("blastoff!");

Counting Down: Revision q The code has the magic number 11, whose relationship with 10 is not represented: System.out.print("T-minus "); for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); System.out.println("blastoff!"); relation? 21

Counting Down: Revision 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? System.out.print("T-minus "); for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); System.out.println("blastoff!");

Counting Down: Revision q Redundant specification: System.out.print("T-minus "); for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); System.out.println("blastoff!");

Counting Down: Revision int N = 10; System.out.print("T-minus "); for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); System.out.println("blastoff!");

Constants 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

Constant 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 final int N = 10; System.out.print("T-minus "); for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); System.out.println("blastoff!");

Variable 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. i's scope public static void example() { int x = 3; for (int i = 1; i <= 10; i++) { System.out.println(x); // // end of example

Why Scope? 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;

Scope Implications 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 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

Class Scope public class CountDown { static int i; public static void main(string[] args) { System.out.print("T-minus "); for (i = 1; i <= 10; i++) { System.out.println( 11 i ); System.out.println("blastoff!"); System.out.println( Final count: + i); // end of main // end of class

Code Beauty Contest : Which One s Better? public class CountDown { static int N = 10; public static void main(string[] args) { System.out.print("T-minus "); for (i = 1; i <= N; i++) { System.out.println( N+1 i +, ); System.out.println("blastoff!"); // end of main // end of class public static void main(string[] args) { System.out.print("T-minus "); int N = 10; for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); System.out.println("blastoff!");

Code Beauty Contest: Which One s Better? int N = 10; System.out.print("T-minus "); for (int i = N; i >= 1; i--) { System.out.print(i +, ); System.out.println("blastoff!"); int N = 10; System.out.print("T-minus "); for (int i = 1; i <= N; i++) { System.out.print(N+1-i +, ); System.out.println("blastoff!");

Nested Loops 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("*"); System.out.println(); // to end the line ********** ********** ********** ********** ********** q The outer loop repeats 5 times; the inner one 10 times. "sets and reps" exercise analogy

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("*"); System.out.println();

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("*"); System.out.println(); q Output: * ** *** **** *****

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); System.out.println();

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); System.out.println(); q Output: 1 22 333 4444 55555

Nested for loop exercise 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 ); System.out.println();

Common Errors 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("*"); System.out.println(); for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; i++) { System.out.print("*"); System.out.println();

Complex lines q What nested for loops produce the following output? inner loop (repeated characters on each line)...1...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 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...1...2..3.4 5 Observation: the number of dots is related to the line number.

Nested for loop exercise q Make a table to represent any patterns on each line....1...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

Nested for loop solution q Answer: for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1 * line + 5); j++) { System.out.print("."); System.out.println(line); q Output:...1...2..3.4 5

Place Introducing Inconsistency? for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1 * line + 5); j++){ System.out.print("."); System.out.println(line);

Fixing for Consistency int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { System.out.print("."); System.out.println(line);

Nested for loop exercise 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++) { System.out.print("."); for (int k = 1; k <= line; k++) { System.out.print(line); System.out.println(); q Answer:...1...22..333.4444 55555

Nested for loop exercise q Modify the code below to produce this output:...1...2...3...4... 5... int N = 5; for (int line = 1; line <= N; line++) { for (int j = 1; j <= (-1 * line + N); j++) { System.out.print("."); for (int k = 1; k <= line; k++) { System.out.print(line); System.out.println();

Nested for loop exercise q Modify the previous code to produce this output:...1...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("."); System.out.print(line); for (int j = 1; j <= (line - 1); j++) { System.out.print("."); System.out.println();

Reuse the Code q Printing a diagonal matrix is a useful task:...1...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("."); System.out.print(line); for (int j = 1; j <= (line - 1); j++) { System.out.print("."); System.out.println();

Recap: Variable Scope 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 );

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