Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Introduction to C Programming
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.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Introduction to Computers and Programming Lecture 5 New York University.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to Computers and Programming Lecture 4: Mathematical and Relational Operators.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Introduction to C Programming
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.
Basic Input/Output and Variables Ethan Cerami New York
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
Arithmetic Operations. Review function statement input/output comment #include data type variable identifier constant declaration.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
Mathematical Calculations in Java Mrs. G. Chapman.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Mathematical Calculations in Java Mrs. C. Furman.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Arithmetic Expressions Addition (+) Subtraction (-) Multiplication (*) Division (/) –Integer –Real Number Mod Operator (%) Same as regular Depends on the.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
What will each of the following lines print? System.out.println("number" ); number645 System.out.println("number" + (6 + 4)+ 5); number105 System.out.println(6.
1 float Data Type Data type that can hold numbers with decimal values – e.g. 3.14, 98.6 Floats can be used to represent many values: –Money (but see warning.
Lecture 3 Java Operators.
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Lecture 3 Expressions Richard Gesick.
Numerical Data Types.
Building Java Programs
Arithmetic Expressions & Data Conversions
Building Java Programs Chapter 2
Expressions and Assignment
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.
Data Types and Expressions
SSEA Computer Science: Track A
Building Java Programs
Building Java Programs
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Building Java Programs
Building Java Programs
Building Java Programs Chapter 2
Building Java Programs
Building Java Programs
Data Types and Expressions
Building Java Programs
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University

Road Map Constants Basic Mathematical Operators Integer Division Operator Precedence Floating point types Other integer types Reading: –Chapter 2: 2.6, 2.7 (excluding 2.7.4), 2.8, 2.11

Review – True / False When System.out.println is called, it always begins printing at the beginning of a new line. All variables must be declared before they are used. All variables must be given a type when they are declared. Java considers the variables number and NuMBer identical. Declarations can appear anywhere in the body of the method main(). A Java program that prints three lines of output must contain three System.out.println() statements.

Review 1.Find the error in each statement: System.println (″The value is ″ + value); //assume there is a variable called value that has been initialized int num1, int num2, int num3; int num#1, num#2, num#3; 2.What is the output for the following Java statements: int x; x = x+1; System.out.println (x); 3.What is the difference between a compile-time and run- time error?

Basic Mathematical Operators

Each of the operators in the table are binary operators. A binary operator acts on two operands Java Operation Arithmetic Operator Algebraic Expression Java Expression Addition +a + b Subtraction -a – b Multiplication *aba * b Division /a / b Modulus %a mod ba % b

Integer Division - The Problem Suppose you have the following code: Using a calculator, the answer is But x can only hold integer values is clearly not an integer value. int x; x = 7 / 4;

Integer Division - Solution To understand the solution, you need to remember your 3 rd Grade Math (really.) 7/4 = 1 (Integer Division) 7%4 = 3 (Modulus Division) The answer: 1 remainder 3

Example: Integer Division // Integer and Modulus Division public class DivMod { public static void main( String args[] ) { int x = 5, y = 10; System.out.println ("5 / 10: " + x/y); System.out.println ("5 % 10: " + x%y); } 5 / 10: 0 5 % 10: 5

Modulus Division (cont.) Second Example: No matter what, your answers must be integers. 5/10 = 0 5%10 =

Odd / Even Numbers Modulus division can also be used to determine whether a number is odd or even. Just divide by 2. If the remainder (modulus) is 0, the number is even. Examples: –10 % 2 = 0. Hence 10 is even. –11 % 2 = 1. Hence 11 is odd. Common Programming Error: Dividing by zero is normally undefined on computer systems and generally results in a fatal error.

Operator Precedence

Here’s another problem. What’s the answer to this? x = * 6; Two Options (depending on the order of operations):  Perform addition first: = 10  10 * 6 = 60  Perform multiplication first: 3*6 =18  7+18 = 25 Which option is correct? Clearly, we cannot have this kind of ambiguity.

Operator Precedence Operator precedence represent rules for evaluating mathematical expressions. Every programming language has similar rules.  2000 Prentice Hall, Inc. All rights reserved.

Operator Precedence Hence, option #2 is always correct (multiplication is performed first): Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: (a + b + c ) / 3 x = * 6; Evaluates to x = = 25

Parentheses Are your friends Are your really good friends Because with them you can ensure expressions are evaluated as you expect Can avoid mistakes with operator precedence (one less thing to think about) –e.g. y = m * x + b ; y = (m * x) + b; –e.g. y = a * b * b + c * b – d; y = (((a * b) * b) + (c * b)) – d;

Floating Point Data Types

double Data Type Data type that can hold numbers with fractional values – e.g. 3.14, 98.6 Doubles can be used to represent many values: –Money (but see warning below) –distance –weight, etc.

double Example // Double Example Program public class Double { public static void main( String args[] ) { double var1, var2, var3, sum; var1 = 87.25; var2 = 92.50; var3 = 96.75; sum = var1 + var2 + var3; System.out.println ("Sum: " + sum); } Sum: 276.5

20 Numeric type ranges in Java Integers Floating point values

Example: Find an Average Suppose you want to determine a student’s average. int totalTests = 4; double average = / totalTests;

Example: Find an Average Problem #1: Operator Precedence –By rules of operator precedence, 100/4 is evaluated first. Hence, average is set to: 302. –To solve this problem, use (): int totalTests = 4; double average = ( )/ totalTests;

Example: Find an Average Problem #2: –90, 92, 95, 100 and 4 are all integers. Hence, this is integer division. –Integer division can result in data truncation (or loss of data.) –Hence, average is set to: 94.0, but the students real average is –There are actually three ways to solve this problem.

Rules of Promotion Promotion: when mixing integers and doubles, all the values are promoted to doubles. In our average example, there are three ways to force promotion, and get the right answer of 94.25: 1. change totalTests to a double: double totalTests = 4.0; double average = ( )/ totalTests;

Rules of Promotion 2.Use a double literal for one of the values on the right hand side double average = ( ) / 4; 3. Use a Cast Operator int totalTests = 4; double average = ( )/(double)totalTests; In this case, totalTests is explicitly cast to a double. And, because we have one double, everything else is promoted. Note that you can also use the (int) cast to cast a double to an integer.

26 constants final int TOTAL_GRADES = 4; Used to avoid “magic numbers” in code. –Only need to change in one place If not, best case must search entire code, worst case you miss a few occurrences. –Choose meaningful names for your constants as you would for any other identifier Unlike variables, you cannot change the value of a symbolic constant. Should be in ALL CAPS (style).

27 more on casting In an assignment statement, you can assign a value of a “less expressive” type to a variable which is “more expressive”. For example: –int gets byte –double gets int –double gets float You must explicitly cast a value of a “more expressive” type to a variable which is “less expressive”. For example: –byte gets (byte) int –int gets (int) double –float gets (float) double –If you do not explicitly cast these values, you will have a syntax error in Java.

Warning about floating point values Floats may be represented differently from what you think by the computer –E.g. 1.9 to you may be –1.9 will not necessarily equal 1.9! In critical calculations for the same reason –E.g..1 added 10 times often will not add up to 1 –Use long integers instead and keep track of where your decimal point is (e.g. $1.75 should be stored as 175)