CSC 204 - Programming I Lecture 5 August 30, 2002.

Slides:



Advertisements
Similar presentations
1 MATH METHODS THAT RETURN VALUES. 2 JAVA'S MATH CLASS.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Types and Arithmetic Operators
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
1 Fundamental Data Types. 2 Outline  Primitive Data Types  Variable declaration  Numbers and Constants  Arithmetic Operators  Arithmetic Operator.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.2 Expressions and Assignment Statement.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Lecture 7. Review Homework 1 (sample solution) Project 1 will be assigned next week –Draw a picture (whatever you want) in the world by using turtles.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING 1 Chapter 2 Writing Java Programs.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
1 Intro to Computer Science I Chapter 2 Fundamental Data Types Java scripting with BeanShell.
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
CSC204 – Programming I Lecture 4 August 28, 2002.
EXPRESSIONS AND ASSIGNMENT CITS1001. Scope of this lecture Assignment statements Expressions 2.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 7: Return values, Math, and double reading: 3.2,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Mathematical Calculations in Java Mrs. G. Chapman.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Arithmetic Expressions in C++. CSCE 1062 Outline Data declaration {section 2.3} Arithmetic operators in C++ {section 2.6} Mixed data type arithmetic in.
Arithmetic OperatorOperationExample +additionx + y -subtractionx - y *multiplicationx * y /divisionx / y Mathematical FormulaC Expressions b 2 – 4acb *
Programs That Calculate. Arithmetic Expressions +addition -subtruction *multiplication /division  Order of Operations BEDMAS (brackets, exponentiation,
1 More data types Character and String –Non-numeric variables –Examples: char orange; String something; –orange and something are variable names –Note.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
CompSci Primitive Types  Primitive Types (base types)  Built-in data types; native to most hardware  Note: not objects (will use mostly first.
4. EXPRESSIONS. Display the value of pi, to 5 decimal places, right justified, in 9 columns Read in someone’s height in feet and inches using.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Dr. Sajib Datta Jan 21,  Declare a variable ◦ int height; [note that no value is still assigned]  Assign a variable a value ◦ height =
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
Introduction to Computer Science / Procedural – 67130
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Java Programming: From Problem Analysis to Program Design, 4e
Writing Java Programs Chapter 2
Arithmetic Operator Operation Example + addition x + y
Chapter 2: Basic Elements of Java
Writing Java Programs Chapter 2
Writing Java Programs Chapter 2
Writing Java Programs Chapter 2
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
Expressions and Assignment
Writing Java Programs Chapter 2
Primitive Types and Expressions
Writing Java Programs Chapter 2
Presentation transcript:

CSC Programming I Lecture 5 August 30, 2002

08/30/2002CSC Programming I2 Recap – tokens and variables  Which of the following is not a token? int i = 0;  Which one of the following is not a variable? int i = 0, j, k = 1;

08/30/2002CSC Programming I3 Literals  A literal is a token that represents a particular number or other value.  Examples of int literals:  Examples of double literals: e1 4.8e+1.48e2 480e-1  The only boolean literals are true and false.  char literals are enclosed within single quotes: 'a' 'z' 'A' 'Z' '0' '9' '%' '.' ' '

08/30/2002CSC Programming I4 Using Literals as Initializers  Literals are often used as initializers: double x = 0.0, y = 1.0; boolean b = true; char ch = 'f';

08/30/2002CSC Programming I5 Modify a Variable  Assignments often use the old value of a variable as part of the expression that computes the new value.  The following statement adds 1 to the variable i : i = i + 1;

08/30/2002CSC Programming I6 Constants  A constant is a value that doesn’t change during the execution of a program.  Constants can be named by assigning them to variables: double freezingPoint = 32.0; double degreeRatio = 5.0 / 9.0;  To prevent a constant from being changed, the word final can be added to its declaration: final double freezingPoint = 32.0; final double degreeRatio = 5.0 / 9.0;

08/30/2002CSC Programming I7 Naming Constants  The names of constants are often written entirely in uppercase letters, with underscores used to indicate boundaries between words: final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0;

08/30/2002CSC Programming I8 Performing Calculations  In general, the right side of an assignment can be an expression.  A literal is an expression, and so is a variable.  More complicated expressions are built out of operators and operands.  In the expression 5 / 9, the operands are 5 and 9, and the operator is /.  The operands in an expression can be variables, e.g. basePrice + salesTax literals, e.g. 5 / 9 other expressions, e.g. length * (width * height)

08/30/2002CSC Programming I9 Operators  Java’s arithmetic operators: + Addition - Subtraction * Multiplication / Division % Remainder  Examples:   4 6 * 2  12 6 / 2  3

08/30/2002CSC Programming I10 Integer Division  If the result of dividing two integers has a fractional part, Java throws it away (we say that it truncates the result).  Examples: 1 / 2  0 5 / 3  1

08/30/2002CSC Programming I11 double Operands  +, -, *, and / accept double operands:   * 2.5  / 2.5  2.44  int and double operands can be mixed:   * 2  / 2  3.05

08/30/2002CSC Programming I12 Binary And Unary Operators  The +, -, *, and / operators are said to be binary operators, because they require two operands.  Java also has two unary arithmetic operators: + Plus - Minus  Unary operators require just one operand.  The unary + and - operators are often used in conjunction with literals ( -3, for example).

08/30/2002CSC Programming I13 Round-Off Errors  Calculations involving floating-point numbers can sometimes produce surprising results.  If d is declared as follows, its value will be rather than 0.1: double d = ;  Round-off errors such as this occur because some numbers (1.2 and 1.1, for example) can’t be stored in double form with complete accuracy.

08/30/2002CSC Programming I14 Operator Precedence  What’s the value of * 3 ?  (6 + 2) * 3, which yields 24?  6 + (2 * 3), which yields 12?  Operator precedence resolves issues such as this.  *, /, and % take precedence over + and -.  Examples: / 2  5 + (2 / 2)  6 8 *  (8 * 3) - 5  * 7  6 - (1 * 7)  –1 9 /  (9 / 4) + 6  % 3  6 + (2 % 3)  8

08/30/2002CSC Programming I15 Associativity  Precedence rules are of no help when it comes to determining the value of  Associativity rules come into play when precedence rules alone aren’t enough.  The binary +, -, *, /, and % operators are all left associative:  (2 + 3) - 4  1 2 * 3 / 4  (2 * 3) / 4  1

08/30/2002CSC Programming I16 Parentheses in Expressions  Parentheses can be used to override normal precedence and associativity rules.  Parentheses in the expression (6 + 2) * 3 force the addition to occur before the multiplication.  It’s often a good idea to use parentheses even when they’re not strictly necessary: (x * x) + (2 * x) - 1  However, don’t use too many parentheses: ((x) * (x)) + ((2) * (x)) - (1)

08/30/2002CSC Programming I17 Assignment Operators  The assignment operator ( = ) is used to save the result of a calculation in a variable: area = height * width;  The type of the expression on the right side of an assignment must be appropriate for the type of the variable on the left side of the assignment.  Assigning a double value to an int variable is not legal. Assigning an int value to a double variable is OK, however.

08/30/2002CSC Programming I18 Compound Assignment Operators  The compound assignment operators make it easier to modify the value of a variable.  A partial list of compound assignment operators: += Combines addition and assignment -= Combines subtraction and assignment *= Combines multiplication and assignment /= Combines division and assignment %= Combines remainder and assignment

08/30/2002CSC Programming I19 Compound Assignment Operators  Examples: i += 2; // Same as i = i + 2; i -= 2; // Same as i = i - 2; i *= 2; // Same as i = i * 2; i /= 2; // Same as i = i / 2; i %= 2; // Same as i = i % 2;

08/30/2002CSC Programming I20 Program: Converting from Fahrenheit to Celsius // FahrenheitToCelsius.java // Converts a Fahrenheit temperature to Celsius public class FahrenheitToCelsius { public static void main(String[] args) { double fahrenheit = 98.6; double celsius = (fahrenheit ) * (5.0 / 9.0); System.out.print("Celsius equivalent: "); System.out.println(celsius); }

08/30/2002CSC Programming I21 Adding Constants to the FtoC Program // FtoC2.java // Converts a Fahrenheit temperature to Celsius public class FtoC2 { public static void main(String[] args) { final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0; double fahrenheit = 98.6; double celsius = (fahrenheit - FREEZING_POINT) * DEGREE_RATIO; System.out.print("Celsius equivalent: "); System.out.println(celsius); }

08/30/2002CSC Programming I22 Methods  A method is a series of statements that can be executed as a unit.  A method does nothing until it is activated, or called.  To call a method, we write the name of the method, followed by a pair of parentheses.  The method’s arguments (if any) go inside the parentheses.  A call of the println method: System.out.println("Java rules!");

08/30/2002CSC Programming I23 The Signature of a Method The signature of a method –Name –Arguments –Return type A class cannot have two methods w hich have the same name and arguments but have different return types

08/30/2002CSC Programming I24 Methods in the Math Class  The Math class contains a number of methods for performing mathematical calculations.  These methods are called by writing Math. name, where name is the name of the method.  The methods in the Math class return a value when they have completed execution.

08/30/2002CSC Programming I25 The pow and sqrt Methods  The pow method raises a number to a power: Math.pow(2.0, 3.0)  8.0 Math.pow(-2.0, 3.0)  –8.0 Math.pow(2.0, -1.0)  0.5  The sqrt method computes the square root of a number: Math.sqrt(2.0)  Math.sqrt(4.0)  2.0  Both pow and sqrt return values of type double.

08/30/2002CSC Programming I26 The abs and max Methods  The abs method computes the absolute value of a number: Math.abs(2.0)  2.0 Math.abs(-2.0)  2.0 Math.abs(2)  2 Math.abs(-2)  2  The max method finds the larger of two numbers: Math.max(3.0, 5.5)  5.5 Math.max(10.0, -2.0)  10.0 Math.max(12, -23)  12 Math.max(-5, -2)  –2

08/30/2002CSC Programming I27 The min Method  The min method finds the smaller of two numbers: Math.min(3.0, 5.5)  3.0 Math.min(10.0, -2.0)  –2.0 Math.min(12, -23)  –23 Math.min(-5, -2)  –5  The value returned by abs, max, and min depends on the type of the argument: If the argument is an int, the methods return an int. If the argument is a double, the methods return a double.

08/30/2002CSC Programming I28 The round Method  The round method rounds a double value to the nearest integer: Math.round(4.1)  4 Math.round(4.5)  5 Math.round(4.9)  5 Math.round(5.5)  6 Math.round(-4.1)  –4 Math.round(-4.5)  –4 Math.round(-4.9)  –5 Math.round(-5.5)  –5  round returns a long value rather than an int value.

08/30/2002CSC Programming I29 Using the Result of a Method Call  The value returned by a method can be saved in a variable for later use: double y = Math.abs(x);  Another option is to use the result returned by a method directly, without first saving it in a variable. For example, the statements double y = Math.abs(x); double z = Math.sqrt(y); can be combined into a single statement: double z = Math.sqrt(Math.abs(x));

08/30/2002CSC Programming I30 Using the Result of a Method Call  Values returned by methods can also be used as operands in expressions.  Example (finding the roots of a quadratic equation): double root1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); double root2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);  Because the square root of b 2 – 4ac is used twice, it would be more efficient to save it in a variable: double discriminant = Math.sqrt(b * b - 4 * a * c); double root1 = (-b + discriminant) / (2 * a); double root2 = (-b - discriminant) / (2 * a);

08/30/2002CSC Programming I31 Using the Result of a Method Call  The value returned by a method can be printed without first being saved in a variable: System.out.println(Math.sqrt(2.0));