CS 112 Introduction to Programming

Similar documents
Building Java Programs

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

Recap: Assignment as an Operator CS 112 Introduction to Programming

Building Java Programs

Building Java Programs

Building Java Programs

Topic 4 Expressions and variables

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

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

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

Lecture 2: Operations and Data Types

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

CS 112 Introduction to Programming

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

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

Building Java Programs

Building Java Programs

Primitive data, expressions, and variables

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Building Java Programs

Java Fall 2018 Margaret Reid-Miller

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Computer Programming

ECE 122 Engineering Problem Solving with Java

Introduction to Computer Programming

CS 112 Introduction to Programming

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

Declaration and Memory

Topic 5 for loops and nested loops

Program Fundamentals

PROGRAMMING FUNDAMENTALS

CSC 1214: Object-Oriented Programming

Lecture Set 4: More About Methods and More About Operators

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

More Programming Constructs -- Introduction

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Basics of Java Programming

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

Chapter 2: Data and Expressions

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

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

Data Conversion & Scanner Class

Zheng-Liang Lu Java Programming 45 / 79

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Operators in java Operator operands.

Chapter 2: Data and Expressions

Repetition with for loops

Introduction to Programming Using Java (98-388)

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

DATA TYPES AND EXPRESSIONS

Lecture Set 4: More About Methods and More About Operators

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

CMPT 125: Lecture 3 Data and Expressions

Chapter 2: Data and Expressions

CS111: PROGRAMMING LANGUAGE II

Chapter 3: Operators, Expressions and Type Conversion

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Expressions & Flow Control

Chapter. Let's explore some other fundamental programming concepts

Chapter 2. Elementary Programming

CS 112 Introduction to Programming

CS 112 Introduction to Programming

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

Java Primer 1: Types, Classes and Operators

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

CS 112 Introduction to Programming

CSI33 Data Structures

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

2: Basics of Java Programming

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

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

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

JAVA Programming Fundamentals

Programming with Java

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

3. Java - Language Constructs I

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

B.V. Patel Institute of BMC & IT, UTU 2014

BM214E Object Oriented Programming Lecture 4

Programming in C++ 6. Floating point data types

Object-Oriented Programming

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

CS110: PROGRAMMING LANGUAGE I

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Primitive Data, Variables, and Expressions; Simple Conditional Execution

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

Expressions and Casting

Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014

Chapter 2 Elementary Programming

Loops and Expression Types

Transcription:

CS 112 Introduction to Programming Variables; Type Casting; Using Variables in for Loops Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q PS2 questions? q Interest in an Informal coding style session? q Informal CS112 lunch together at Commons 2 1

Recap: Data Types q Why data types? Define the data representation, allowed operations, and semantics of operations (e.g., 1 / 2 vs 1.0 / 2.0) q Java is a strong typed language: every variable, every literal has a type int na; na = 4; int nb = 1; int total = na * 4 + nb * 3; System.out.println( total / (na + nb) ); double GPA = 3.0 + 0.8; char lastnameinitial = Y ; 3 Recap: Mixed Type q Why mixed types? Desired result in a different type Natural expression, 4 / 8.0; 3 + 1 q Mix-type operations Java tries a set of predefined conversion rules, e.g., numerical promotion Conversion is per operator 4 2

Example: Mixed Arithmetic Expression 2.5 + 10 / 3 * 2.5-6 / 4 \ / 2.5 + 3 * 2.5-6 / 4 \ / 2.5 + 7.5-6 / 4 \_/ 2.5 + 7.5-1 \ / 10.0-1 \ / 9.0 (not 9!) Practice: Mixed Arithmetic Expression 7 / 3 * 1.2 + 3 / 2 \_/ 2 * 1.2 + 3 / 2 \ / 2.4 + 3 / 2 \_/ 2.4 + 1 \ / 3.4 3

Data Conversion Rule: Numeric to Java String q Occurs automatically when one operand is a number and the other a string in the + operator q The conversion is per-operator, affecting only its operands. q This produces the convenient string concatenation operation. 7 Java String Concatenation Conversion: Examples 1 + "abc" + 2 is "abc" + 1 + 2 is 1 + 2 + "abc" is "abc" + 9 * 3 is 4-1 + "abc" is "1abc2" "abc12" "3abc" "abc27" "3abc" 4

Examples q See IntOps.java q Fix the GPA.java program 9 An Alternative: Type Casting q type cast: An explicit, FORCED conversion from one type to another. q Syntax: (type) expression Potentially q Type casting has high precedence and casts only the item immediately next to it. q You can cast either up (promotion) or down (truncate) 5

Type Casting Examples double result = (double) 19 /5; // 3.8 int result2 = (int) result; // 3 double x = (double) 1 + 1 / 2; // 1.0 double y = 1 + (double) 1 / 2; // 1.5 Outline q Admin and recap q Variables: more details 12 6

Variable Details q A variable can only store a value of its own type. q Mixed type allowed only if allowed by automatic numeric promotion int x; x = 2.5; // ERROR: incompatible types double mygpa = 4; mygpa 4.0 double avg = 11 / 2; avg 5.0 Variable Details q A variable can't be used until it is assigned a value. int x; System.out.println(x); // ERROR: x has no value q You may not declare the same variable twice. int x; int x; // ERROR: x already exists int x = 3; int x = 5; x = 5; // OK: declare and initialize // ERROR: x already exists // this is OK 7

Update vs. Algebra q What happens here? int items = 3; items = items + 1; //??? items 34 items = items + 1; 15 Example: Ruler public class Ruler { public static void main(string[] args) { String ruler = "1"; ruler = ruler + " 2 " + ruler; ruler = ruler + " 3 " + ruler; ruler = ruler + " 4 " + ruler; System.out.println(ruler); "1" "1 2 1" "1 2 1 3 1 2 1" % java Ruler 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 8

Update Shorthand q Since increment updates are common, Java introduces shorthand: count = count + increment; count += increment; These expressions have the same effect count = count + 1; count += 1; count ++; when increment is 1 count ++; 17 Modify-and-assign shortcuts to modify a variable's value Shorthand Equivalent longer version variable ++; variable = variable + 1; variable --; variable = variable - 1; 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); int x = 2; double gpa = 3.8; x += 3; gpa --; x *= 2; x *= 2 + 1; // x = x + (3) -> 5; // gpa = gpa 1.0 -> 2.8; // x = x * 2 -> 10; // x = x * (2+1) -> 30; 9

General: Assignment/Modify-and-Assign as Operators q You can consider assignment/modify-and-assign as operators, 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 used to calculate in the variable on the left hand side. 19 Practice q Compile the list of operators that we covered and their precedence levels 20 10

Example: StockSuccess q What is the result of adding $1000 on Jan. 1 of each year to a stock account fully invested in S&P500 index ETF? 2008: -38.5% 2009: 23.45% 2010: 12.78% 2011: 0.00% 2012: 13.4% 2013: 29.60% http://www.1stock1.com/1stock1_141.htm 21 Outline q Admin q Variables q for Loops 22 11

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 23 Flowchart of a for loop for ( initialization ; condition ; increment ) statement; initialization condition evaluated true false statement increment 24 12

The for Statement: Example for (int counter = 1; counter <= 3; counter ++) { System.out.println ( counter ); // beginning of the next statement Establish initial value of control variable. int counter = 1 Determine if final value of control variable has been reached. counter <= 3 false true println(counter) Body of loop (this may be multiple statements) counter ++ Increment the control variable. 25 Flexibility of for Loop with Counter Loop counter: can use any name, not just i can start at any value, not just 1 only valid in the loop Compare loop counter with target: < less than <= less than or equal to > greater than >= greater than or equal to Can increment, decrement, times, for (int i = 1; i <= 6; i ++) { System.out.println("I am so smart"); 13

Using for Loops q Java's for loop statement performs a task many times. Using for Loops? 14

Using for Loops for (int i = 1; i <= 3; i++) { System.out.println( Now Facebook ); System.out.println( Now Twitter ); System.out.println( Now Tumblr ); Counting Down q Write a program generating output T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff! q Requirement: loop counter starts with 10 and counts down 15

Counting Down v1 q The update uses -- to count down. System.out.print("T-minus "); for (int i = 10; i >= 1; i--) { System.out.print(i + ", "); System.out.println("blastoff!"); Counting Down v2 q Requirement: loop counter starts with 1 and counts up: 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!"); 16

Mapping Loop# to Target Pattern y = 11 - x 11 i number to print 1 10 2 9 3 8 4 7 5 6 10 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9 10 11 33 Counting Down System.out.print("T-minus "); for (int i = 1; i <= 10; i++) { System.out.println( 11 i +, ); System.out.println("blastoff!"); y = 11 - x 11 10 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9 10 11 17

An IQ Test Format? 10 9 8 7 6 5 4 3 2 1-1 -1-1 -1-1 -1-1 -1-1 35 An IQ Test Format? 10 9 8 7 6 5 4 3 2 1-1 -1-1 -1-1 -1-1 -1-1 -1 36 18

An IQ Test Format 11 10 9 8 7 6 5 4 3 2 1-1 -1-1 -1-1 -1-1 -1-1 -1 37 An IQ Test Format Loop # i: Value at 0 11 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1-1 -1-1 -1-1 -1-1 -1-1 -1 y = 11 - x slope 11 10 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9 10 11 38 19

Practice: Mapping loop# to numbers for (int count = 1; count <= 5; count++) { System.out.print(... ); What statement in the body would cause the loop to print: 17 13 9 5 1 Mapping loop# to numbers Loop# i: Target: 21 1 2 3 4 5 17 13 9 5 1 21 4*i -4-4 -4-4 for (int count = 1; count <= 5; count++) { System.out.print(-4 * count + 21 + " "); 40 20

Practice: Mapping loop# to numbers for (int count = 1; count <= 5; count++) { System.out.print(... ); What statement in the body would cause the loop to print: 4 7 10 13 16 for (int count = 1; count <= 5; count++) { System.out.print(3 * count + 1 + " "); Practice: Mapping loop# to numbers for (int count = 1; count <= 5; count++) { System.out.print(... ); What statement in the body would cause the loop to print: 2 7 12 17 22 for (int count = 1; count <= 5; count++) { System.out.print(5 * count - 3 + " "); 21

Counting Down: v3 q If I want to count down from 12, what should we 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: v3 q Problem: The code has two magic numbers 11 and 10, but they are not independent System.out.print("T-minus "); for (int i = 1; i <= 10; i++) { System.out.print(11-i +, ); System.out.println("blastoff!"); relation? 44 22

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!"); 45 Code Summary 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!"); 46 23

Counting Down: v4 Does the following program give the correct countdown?: int N = 10; System.out.print("T-minus "); for (int i = 1; i <= N; N++) { System.out.print(N+1-i +, ); System.out.println("blastoff!"); 47 Counting Down: v4 Does the following program gives the correct countdown?: int N = 10; System.out.print("T-minus "); for (int i = 1; i <= N; N++) { System.out.print(N+1-i +, ); System.out.println("blastoff!"); Answer: No. There is a typo (N for i) Q: can the computer help me to find it (read my mind?) 48 24

Constant q Use keywords to tell computer your intension 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 49 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!"); 50 25

Backup Slides 51 Type Conversions in Java q Identity conversion (i.e., no conversion) q Conversions related to primitive data types widening primitive conversions narrowing primitive conversions q Conversions related to classes widening reference conversions narrowing reference conversions we will cover these two cases later in the course; they are powerful tools to allow polymorphism q Conversions related to Strings string conversions: i.e., convert a numerical data to a string, e.g., the number 17 to the string 17 52 26

Widening Primitive Conversions q Widening primitive conversions are those that do not lose information about the overall magnitude of a numeric value q Java defines 19 primitive conversions as widening primitive conversions byte short, int, long, float, double short int, long, float, double char int, long, float, double int long, float, double long float, double float double q They are generally safe because they tend to go from a small data type to a larger one (such as a short to an int) can potential problems happen in some of the cases? 53 Narrowing Primitive Conversions q Java defines 23 primitive conversions as narrowing primitive conversions byte char short byte, char char byte, short int byte, short, char long byte, short, char, int float byte, short, char, int, long double byte, short, char, int, long, float q Narrowing primitive conversions may lose either overall magnitude of a numeric value and/or precision 54 27

Assignment during Declaration q You can assign a value to a variable when declaring it. This is called initialization q Syntax: <type> <name> = <expression>; int x = (11 % 3) + 12; x 14 double mygpa = 3.95; mygpa 3.95 Example: Receipt q Once given a value, a variable can be used in expressions: public class Receipt { public static void main(string[] args) { // Calculate total owed // assuming 6% tax / 15% tip int subtotal = 38 + 40 + 30; double tax = subtotal *.06; double tip = subtotal *.15; double total = subtotal + tax + tip; System.out.println("Subtotal: " + subtotal); System.out.println("Tax: " + tax); System.out.println("Tip: " + tip); System.out.println("Total: " + total); 28

Update Variables q You can update variable values: int x; x = 3; System.out.println(x + " here"); x 11 3 // 3 here x = 4 + 7; System.out.println("now x is " + x); // now x is 11 Example: StockSuccessSimple q Stock market average return 8.5%. What is the total asset after saving $1000 every year for 50 years? 58 29