Numerical Data Recitation – 01/30/2009

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
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.
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
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.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
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.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 3 Numerical Data.
Chapter 5: Methods 1. Objectives To declare methods, invoke methods, and pass arguments to a method (§ ). To use method overloading and know ambiguous.
Chapter 2 Elementary Programming
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 3: Numerical Data Manipulating Numbers Variables.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 3 Console Output Keyboard Input Numerical.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 4 Methods Chapter.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
The Math Class Methods Utilizing the Important Math Operations of Java!
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
1 Java Library Lecture 9 by Dr. Norazah Yusof. 2 Java Library Java has pre-defined classes that consist of the basic language classes in Java (organized.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
Numeric Data Types There are six numeric data types: byte, short, int, long, float, and double. Sample variable declarations: int i, j, k; float numberOne,
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
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.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Lecture 5: java.lang.Math, java.lang.String and Characters Michael Hsu CSULA.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
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.
Chapter 4 Mathematical Functions, Characters, and Strings 1.
Chapter 4 Mathematical Functions, Characters, and Strings
Chapter 2 Basic Computation
Elementary Programming
Multiple variables can be created in one declaration
Primitive and Reference Data Values
Java Programming: From Problem Analysis to Program Design, 4e
IDENTIFIERS CSC 111.
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Mathematical Functions, Characters, and Strings
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Java Fundamentals
Chapter 5 Methods.
CS2011 Introduction to Programming I Elementary Programming
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

Numerical Data Recitation – 01/30/2009 11 Numerical Data Recitation – 01/30/2009 CS 180 Department of Computer Science, Purdue University

Project 2 Now posted on the class webpage. Due Wed, Feb. 4 at 10 pm. Start early! All questions on the class newsgroup. Evening consulting hours MTW 7-10 p.m. in LWSN B146.

Data Types Primitive Data Types Reference Data Types Numeric byte, short, int, long, float, double Character char Logic boolean Reference Data Types Object Note: Primitive data items are created upon declaration. No need to use new to allocate space.

Variables Three properties Example Memory location Data type Name int x; // declaration Memory space is allocated to store integer values x is the reference name for the memory space x = 3; // assignment The value 3 is stored at the memory space x x = 5; // another assignment The value 5 is stored at x to replace the old value 3

Variables (cont.) Another example Similar to the object assignment int y = 10; Variable y is declared and also initialized to 10 x = y; Remember: x is 5 from the previous slide Now the value stored in y is copied to the memory location of x: Now x is 10! Similar to the object assignment Student student1, student2; student1= new Student(); student2= student1; student2 now refers to student1 (reference is copied from student1 to student2)

Numeric Data Types Six data types: byte, short, int, long, float, double A mistake in the original table. See below

Arithmetic Operations Arithmetic operations that can be used on the numeric data

Division and Modulo Division ‘/’ Modulo ‘%’ Integer division 5 / 4 = 1 1 / 2 = 0 When either or both numbers are float or double, then the result is a real number 5.0 / 4 = 1.25 1.0 / 2.0 = 0.5 3.2 / 1.6 = 2.0 Modulo ‘%’ Returns the remainder of a division, usually involves only integers Examples: 23 % 5 = 3 23 % 25 = 23 16 % 2 = 0 For both: the second number cannot be 0!

How to calculate the area? Problem Given a circle with radius r = 5, what is the area of the circle (let )? Hint: The formula is where is the area of the circle Solution int r = 5; final double PI = 3.14; // PI is a constant! double s = PI*r*r; // s is double! System.out.println(“The area of the circle is: ” + s); Output The area of the circle is: 78.5

Precedence Rules When evaluating the arithmetic expressions, we need to follow the precedence rules to decide which operation/subexpression to evaluate first:

What is unknown? The code: The evaluation: c – 1 = 4 – 1 = 3 int a = 1; int b = a * 3; int c = a + b; int unknown = a + b * c % (b / (c - 1)) The evaluation: c – 1 = 4 – 1 = 3 b / (c -1) = 3 / 3 = 1 b * c = 3 * 4 = 12 b * c % (b / (c-1)) = 12 % 1 = 0 unkown = a + 0 = 1!

Typecast Low precision -> high precision Implicit typecasting byte -> short -> int -> long -> float -> double Implicit typecasting From lower precision to higher precision e.g. double x = 3; int x = 2.5; // wrong! int x = (int)2.5; // right! x = 2 The above is called explicit demotion Explicit typecasting double x = (double)5/2; double y = (double)(5/2); Typecast operator: (double), cast int to double Result: x = 2.5, y = 2.0. Why?

Constant Sometimes we want a value to remain the same, then we use constants Usage final double PI = 3.14; final int MAX_SCORE = 100; “final” is a keyword; “PI”, “MAX_SCORE” are named constants; “3.14”, “100” are literal constants Benefits Consistent and unchanged value Easy to manage, more readable

What does this program do? Input: a cylinder with radius 1 and height 10 The program: int radius = 1; final double PI = 3.14; int height = 10; double x = 2 * PI * radius; double y = PI * radius * radius; double result = 2 * y + x * height; So, the result is 2 * PI * radius (radius + height) = 69.08 What is this?

How can I get numbers from strings? Suppose the radius and height of the cylinder are provided in the form of strings: e.g. “1” and “10”. How can we get the actual number? Let the strings for radius and height be r and h. Here is the code for conversion: int radius = Integer.parseInt(r); int height = Integer.parseInt(h); If radius and height can be real numbers, the safer way to do this is: double radius = Double.parseDouble(r); double height = Double.parseDouble(h);

How can I print numbers nicely? In the previous cylinder example, if we want to display the result with only two digits after the decimal point, here is what we can do: DecimalFormat df = new DecimalFormat(“0.00”); System.out.println(df.format(result)); Operator overloading The result is the surface area of the cylinder! We can display the result more clearly like this: System.out.println(“The surface area of the cylinder: ” + TAB + df.format(result)); Here “+” is an overloaded operator Not addition here, but concatenation Output: “The surface area of the cylinder: 69.08” What’s the difference between the following two? System.out.println(“Surface area: ” + (1 + 1)); System.out.println(“Surface area: ” + 1 + 1);

Math Class Math class is very powerful. It provides all kinds of useful methods such as: abs(a): absolute value of a max(a, b): the larger of a and b min(a, b): the smaller of a and b pow(a, b): a raised to power b round(a): a rounded to the nearest whole number sqrt(a): square root of a ceil(a): smallest whole number no less than a floor(a): largest whole number no bigger than a sin(a): trigonometric sine of a cos(a): trigonometric cosine of a exp(a): natural number e(2.718…) raised to power a

Sample Code What is the output? Other examples double a = 10.5; int b = -20; b += (int)a; // shorthand double c = Math.max(Math.abs(b), (int)(a + 1)); c *= 11; // shorthand System.out.println(“c = ” + Math.sqrt(c)); What is the output? Other examples Math.pow(2.0, 3.0) = 8.0 Math.floor(3.4) = 3, Math.ceil(3.4) = 4 Math.round(3.4) = 3, Math.round(3.6) = 4 Math.sin(Math.PI/2) = 1.0 Math.cos(Math.PI/2) = 0.0

Random Numbers Math.random() Generates a number (double) no less than 0 and less than 1, i.e. in the range [0, 1) How to generate a random integer between min and max, i.e. in the range [min, max]? int randomNumber = (int)(Math.floor(Math.random() * (max-min+1)) + min); Why is this correct? [0, 1)* (max – min +1)  [0, max – min + 1) After applying Math.floor, the range becomes [0, max – min] After adding min, the range becomes [min, max] After the explicit typecasting, the random number becomes an integer between min and max

Demo: Java Error Information Program – test.java Import java.util.*; class test{ public static void main(String[] args) { System.out.println(“Enter an integer: ”); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println(“Integer entered: ” + n); } Now try the following and compile. Observe the error information: Remove “;” Remove “int” before “n” Change “scanner.nextInt()” to “Scanner.nextInt()” Change “scanner.nextInt()” to “scanner.nextInt”

Quiz What’s wrong with the following piece of code? Does it compile? How will you correct the errors? double x = sqrt(9.0); int y = Math.abs(-3.2); y += x; double z = (double) y / (1/2); System.out.println(“z is ” + z);