Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Similar documents
Chapter 2. Elementary Programming

CEN 414 Java Programming

Primitive Data, Variables, and Expressions; Simple Conditional Execution

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

ECE 122 Engineering Problem Solving with Java

CIS133J. Working with Numbers in Java

More Programming Constructs -- Introduction

Lecture Set 4: More About Methods and More About Operators

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

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

HOW TO DIVIDE: MCC6.NS.2 Fluently divide multi-digit numbers using the standard algorithm. WORD DEFINITION IN YOUR WORDS EXAMPLE

Full file at

Data Conversion & Scanner Class

Lecture Set 4: More About Methods and More About Operators

Introduction to Computer Science Unit 2. Notes

Chapter 2: Data and Expressions

Operators. Java operators are classified into three categories:

CS313D: ADVANCED PROGRAMMING LANGUAGE

Expressions and Casting

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

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

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

Course Outline. Introduction to java

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

AP CS Unit 3: Control Structures Notes

Lecture 2: Operations and Data Types

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

Introduction to Java Applications

Chapter 2: Data and Expressions

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

JAVA OPERATORS GENERAL

A variable is a name for a location in memory A variable must be declared

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

CS111: PROGRAMMING LANGUAGE II

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

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

Chapter 2: Data and Expressions

Chapter 2 Primitive Data Types and Operations. Objectives

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

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

Gateway Regional School District VERTICAL ALIGNMENT OF MATHEMATICS STANDARDS Grades 3-6

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

double float char In a method: final typename variablename = expression ;

Program Fundamentals

Eng. Mohammed S. Abdualal

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Example: Tax year 2000

JAVA Programming Concepts

CSC 1214: Object-Oriented Programming

Calculations, Formatting and Conversions

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

Chapter. Let's explore some other fundamental programming concepts

Introduction to Computer Science Unit 2. Notes

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Chapter 3. Selections

Learning Log Title: CHAPTER 3: ARITHMETIC PROPERTIES. Date: Lesson: Chapter 3: Arithmetic Properties

CMPT 125: Lecture 3 Data and Expressions

Imelda C. Go, South Carolina Department of Education, Columbia, SC

What did we talk about last time? Examples switch statements

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Java Reference Card. 1. Classes. 2. Methods. 3. Conditionals. 4. Operators

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Prof. Navrati Saxena TA: Rochak Sachan

DATA TYPES AND EXPRESSIONS

Chapter 2 - Introduction to C Programming

Zheng-Liang Lu Java Programming 45 / 79

COMP 110 Introduction to Programming. What did we discuss?

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

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

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Arithmetic Expressions in C

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Welcome to the Primitives and Expressions Lab!

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Unit 1 Lesson 4. Introduction to Control Statements

More types, Methods, Conditionals. ARCS Lab.

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

The ALU consists of combinational logic. Processes all data in the CPU. ALL von Neuman machines have an ALU loop.

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

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

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

Chapter 2 Elementary Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

COMP 202 Java in one week

Computer Components. Software{ User Programs. Operating System. Hardware

COMP 202 Java in one week

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

Python Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Chapter 3: Operators, Expressions and Type Conversion

Transcription:

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY Arithmetic Operators There are four basic arithmetic operations: OPERATOR USE DESCRIPTION + op1 + op2 Adds op1 and op2 - op1 + op2 Subtracts op2 from op1 * op1 + op2 Multiplies op1 and op2 / op1 + op2 Divides op1 by op2 The operands of the arithmetic operators must be of a numeric type The order of operations is the same as it is in algebra (BEDMAS!): o Parenthesis () o Multiplication/division o Addition/subtraction All terms are evaluated left to right Remainder Operator The remainder (%) operator will produce the remainder of a division operation o (Equivalent to mod in Turing) o 7 / 2 = 3 2 goes into 7 evenly 3 times, with 1 left over (2*3 = 6) o 7 % 2 = 1 leftover from 7 / 2 is 1 Another example: o 7 / 4 = 1 o 7 % 4 = 3 Applying the remainder operator: o The remainder operator is useful in lots of situations where floating point is not appropriate, for example, some types of monetary and date calculations public class Change public static void main(string [] args) int pennies = 23; int nickels = 84; int dimes = 74; int piggybank, cents, dollars;

piggybank = pennies + nickels*5 + dimes*10; dollars = piggybank / 100; cents = piggybank % 100; System.out.println( Dollars = + dollars); System.out.println( Cents = + cents); Run this code. What is the output? Type Conversion Sometimes it is convenient (or necessary) to convert data from one data type to another. For example, arithmetic operations require both operates and the result to be of the same type (example: you have to add two ints and assign the result to an int for an expression to work) Conversions between data types must be handled carefully to avoid losing information Conversions fall into one of two categories: o Widening conversion (safest conversion): converting data from a smaller data type to a larger one (e.g. short int). Widening conversions move left to right on the following scale: Smallest data type... Largest data type byte short int long float double These are done automatically by the system. Example: float b = 7/4; System.out.println( B is: + b); In the above example, the numbers 7 and 4 are integers. Integer math is performed on these two operands. Then, the result is converted to a float automatically, and is assigned to the variable b. Type in and run this example. What is the value of b? What happens when we assign a value in this way? How do we avoid the above loss of information? int a = 5; int b = 10; float result; result = (float) a / b; // result is 0.5 First a will be converted to a float, then b will automatically be converted to a float as well so that float division will be used (both operands must be float). Then, the float result will be stored in result.

o Narrowing conversion (more risky conversion): can lose information because data is converted from a larger type to a smaller type (e.g. int short). Will cause compiler errors unless explicitly requested by the use of a cast. They move right to left on the above scale. Example 1: Example 2: int dollars; double money = 121.35; // cast is (int) in the next line dollars = (int) money; //will put 121 in dollars short x = (short) 32000; byte y = (byte) x / 1000; In this example, you are attempting to divide two numbers. Since both operands need to be the same type, Java will assume x and 1000 are both shorts, and the result will be a short as well. Since we need a result of type byte, we need to cast the result to a byte. We do this by placing the name of the desired type in parentheses after the assignment operator. The Math Class Java s Math class provides a variety of methods for performing advanced mathematical operations. All of the methods are static (which you will learn about later), and can be used directly. Typical methods (functions): double Math.sin(double) //returns sine of argument double Math.floor(double) //returns largest integer less than or equal to argument double Math.rint(double) //returns the nearest integer to the argument double Math.random() //returns a random number in the range of [0, 1) double Math.sqrt(double) //returns the square root of the number CONSTANTS double Math.PI //approximately 3.14 double Math.E //approximately 2.72

Random Number Generator The Math class has a method that generates a random number between 0.0 and 1.0 1. To generate a random number between 0.0 and 1.0: Math.random(); 2. To generate a random integer between 0 and n 1: (int) (Math.random() * n); 3. To generate a random integer between 1 and n: (int) (Math.random() * n ) + 1; public class RandomNumberDemo public static void main(string[] args) int n = 6; double x = Math.random(); int y = (int) (Math.random() * n); int z = (int) (Math.random() * n) + 1; What is the difference between x, y, and z? What range of values can x, y and z have? PRPGRAMMING PRACTISE 1. Try the following statements to learn more about how Java performs arithmetic operations. Try to predict what will happen (and if the code will work), then add System.out.print() statements after each of the following lines to output the variable s final value (if the code works!): int a = 7 / 4; int b = 7.0 / 4; float c = 7 / 4; float d = 7.0 / 4; float e = 7.0f/ 4; // appending an f after a real number tells Java it s a float value double f = 7.0 / 4.0; double g = 7.0f / 4.0; 2. Write a program that generates random numbers until it finds one that has a value greater than 0.75. Use a while loop, and a flag variable (sentinel) to exit your loop. 3. Write a program that calculates the radius of a circle in feet and inches. Hint: Use the square root method of the Math class. Feet and inches should be int variables, while radius and circlearea should be double type variables.

4. Write a program that converts an ugly-looking double value to a nice real number with 2 decimal digits. Hint: you will need to use the Math.rint method, and you will need to multiply by 100.0 and then divide by 100.0 to make this work. 5. Write a program to determine whether a year is a leap year or not. A year is a leap year if it is evenly divisible by 4 but not evenly divisible by 100 unless it is also evenly divisible by 400. For example: 1996 is a leap year evenly divisible by 4 but not evenly divisible by 100. 1990 is not a leap year evenly divisible by 4 and 100, but not divisible by 400. 2000 is a leap year evenly divisible by 4, 100, and 400. Hint: you will need the % operator, as well as several if-else statements. 6. Write a program that checks numbers from 1 to 100 to see if they are prime or not. Output all numbers that are prime. Hint: you will need the % operator and you will also find the break statement useful.