CS2011 Introduction to Programming I Elementary Programming

Slides:



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

Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
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.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Mathematical Operators: working with floating point numbers and more operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this.
Numerical Data Recitation – 01/30/2009
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.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Overview CS2336: Computer Science II1. First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (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.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Chapter 2 Elementary Programming
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 3: Numerical Data Manipulating Numbers Variables.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by
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:
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles.
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.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
CompSci 230 S Programming Techniques
Chapter 2 Elementary Programming
Chapter 2 Basic Computation
Chapter 4 Assignment Statement
Unit 2 Elementary Programming
Elementary Programming
Chapter 2 Elementary Programming
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Chapter 3 Assignment Statement
Chapter 2 Elementary Programming
Data types, Expressions and assignment, Input from User
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Chapter 2 Elementary Programming
IDENTIFIERS CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Numerical Data Types.
Chapter 2: Basic Elements of Java
Fundamentals 2.
Chapter 2: Java Fundamentals
Chapter 2 Elementary Programming
Expressions and Assignment
elementary programming
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Primitive Types and Expressions
Chapter 2: Java Fundamentals cont’d
Chapter 2 Primitive Data Types and Operations
Chapter 2: Beginning to Program
Presentation transcript:

CS2011 Introduction to Programming I Elementary Programming Chengyu Sun California State University, Los Angeles

Overview Variables and Constants More operators Data types More operators And Math.pow() More about literals (i.e. values) Type mismatch and conversion Input using Scanner Put everything together

Example: Circle Measurements Write a program that displays the diameter, perimeter, and area of a circle that has a radius of 6.5

CircleMeasurements.java public class CircleMeasurements {   public static void main(String args[]) {     System.out.println("Diameter is " + 6.5 * 2);     System.out.println("Perimeter is " + 2 * 3.14159 * 6.5);     System.out.println("Area is " + 3.14159 * 6.5 * 6.5); }

Problem with CircleMeasurements.java public class CircleMeasurements {   public static void main(String args[]) {     System.out.println("Diameter is " + 6.5 * 2);     System.out.println("Perimeter is " + 2 * 3.14159 * 6.5);     System.out.println("Area is " + 3.14159 * 6.5 * 6.5); } Repeating the same value multiple times is bad Tedious to type Easy to make mistake (i.e. typo)

Use a Variable double radius = 6.5; Type Variable Name Variable Value double radius = 6.5; System.out.println("Diameter is " + 2*radius); System.out.println("Perimeter is " + 2*3.14159 * radius); System.out.println("Area is " + 3.14159* radius*radius);

Why Repeating Variables Is Better Variable name is more descriptive, which makes the code more readable, thereby easier to understand and debug Variable is more reusable, e.g. set radius to a different value and use the same formula Compiler/IDE can help finding typos

Create A Variable double radius = 6.5; double radius; radius = 6.5; // Declare a variable // Assign a value to a variable Variables can be declared anywhere in a method A variable can only be used after it’s declared

Variable Declaration double radius; Data Type Name Computer Memory Compiler allocates a space in computer memory based on the size required by the data type Name will be used to refer to whatever value stored in the space

Data Types in Java Primitive types Class types E.g. int, float, double, boolean Type name starts with a lowercase letter Class types E.g. String Type name starts with a uppercase letter

Primitive Numerical Types Name Range Size byte -27 to 27-1 1 byte short -215 to 215-1 2 bytes int -231 to 231-1 4 bytes long -263 to 263-1 8 bytes float Very large double For integer numbers like -2, 100 For numbers with a fraction, e.g. -2.5, 3.1415 When unsure, use int and double

About float and double float: single-precision floating point numbers double: double-precision floating point numbers Because they use limited storage space to represent infinite possible values, some values may not be represented exactly (though usually they are accurate enough) double is more accurate than float

Assignment Statement radius = 6.5; Assignment operator Assign the value on the right to the variable on the left Right-hand side can be an expression = is assignment, not equals

Some Other Forms of Variable Declaration/Assignment int a, b, c, d; double x, y=2.5, z; a = b = c = 10; d = a + b + c; Assignment operator = is right associative (i.e. evaluates from right to left) Arithmetic operators like + are left associative (i.e. evaluates from left to right)

Constant final double PI = 3.14159; A constant is basically a variable whose value cannot be changed Usually used to represent some value that should remain unchanged throughout a program Naming convention All capital letters Use _ to concatenate multiple words

More About Numerical Operators +, -, *, / + is also used for string concatenation The remainder (a.k.a. modulus) operator % The result is the remainder (i.e. the amount left over) after a division, e.g. 9%2=1 Example: PrintDigits.java

Associativity and Precedence Precedence determines the order of evaluation of different operators Associativity determines the order of evaluation of operators with the same precedence For example, what's the result of the following expression?? 1 + 2 * 3 + 4 * 5 % 6 - 7

Convenience Operators … Certain operations are used so often that they get their own operators Use the value of a variable, does some calculation, then assign the result back to the variable Increment and decrement by 1

… Convenience Operators n = n + 10 n = n – 10 n = n * 10 n = n / 10 n = n % 10 n += 10 n -= 10 n *= 10 n /= 10 n %= 10 ++n n++ Pre-increment n = n + 1 Post-increment --n n-- Pre-decrement n = n - 1 Post-decrement

Exercise: Pre/Post Increment/Decrement int a = 1, b = 1; int c1 = 10 + ++a * 10; int c2 = 10 + b++ * 10; a = b = 1; c1 = 10 + --a * 10; c2 = 10 + b-- * 10;

Math.pow(x,y) It is a method, not an operator Used for calculating x to the power of y For example: 23 Math.pow(2,3) 8

Types of Literals "Welcome to Java!" String 10 byte, short, int, or long ?? 10.5 float or double??

Other Forms of Literals Type Notes 10l or 10L long 10.5f or 10.5F float 1.1e2 or 1.1E2 double scientific notation 10 int decimal (i.e. base 10) 0b10 or 0B10 binary (i.e. base 2) 0710 octal (i.e. base 8) 0x10 or 0X10 hexadecimal (i.e. base 16)

Type Mismatch short a; int b; float c; double d; a = 1000000; // ??

Type Mismatch short a; int b; float c; double d; a = 1000000; // error. overflow b = 1000000; // ok c = 1000000; // ok d = 1000000; // ok a = 3.6; // error. Loss of data b = 3.6; // error. Loss of data c = 3.6; // error. Loss of precision d = 3.6; // ok

Implicit Type Conversion A.K.A. Coercion Happens when converting a type with a smaller range to a type with a larger range, e.g. short  int int  long float  double

Explicit Type Conversion A.K.A. Casting Needed when converting a type with a larger range to a type with a smaller range Must be explicitly specified by the programmer, e.g. int n = (int) 3.6;

Result Types When Mixing Types in an Expression "The result is " + 10 + 2 ?? "The result is " + (10 + 2) ?? 10 / 3 * 3 ?? 10.0 / 3 * 3 ?? 10 / 3.0 * 3 ?? 10 / 3 * 3.0 ??

Circle Measurements with Input Modify the Circle Measurements example so that it lets a user to enter the value of the radius

Console Output and Input System.out Console output System.in Console input Unfortunately, unlike System.out which has convenient methods like println(), System.in is pretty difficult to use

Use Scanner So the common practice is use a Scanner to wrap around System.in Type Variable Create a new scanner Scanner in = new Scanner( System.in ); // Read user input ... // Close the scanner in.close();

About Import Scanner is a not class included by the compiler by default, so it has to be imported: import java.util.Scanner; It's easy to let Eclipse do the import Click on the light bulb next to the error mark

Commonly Used Methods in Scanner nextByte() nextShort() nextInt() nextLong() nextFloat() nextDouble() nextLine() Use Eclipse's autocomplete function

Example: Compute Average Read three values from console and output the average

So Where Are We? Comments Project Packages Classes Variables Methods Statements Statements Expressions Literals Variables Operators

Put Everything Together – Mortgage Calculator See the mortgage calculator at bankrate.com Given Home price Down payment percentage Mortgage term (in years) Annual interests rate Display monthly payment

How Do We Do It? Find the monthly payment formula (or in Computer Science terms, the algorithm) Outline the steps in comments (i.e. pseudo-code) Implement each step Verify the result (i.e. test and debug)

Readings Chapter 2 of the textbook (there will be a quiz next week)