Chapter 2. Elementary Programming

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

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

Chapter 2 Elementary Programming

CEN 414 Java Programming

Chapter 2 Elementary Programming

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Chapter 2 Elementary Programming

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 Primitive Data Types and Operations. Objectives

JAVA Programming Concepts

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

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

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

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Chapter 2 Primitive Data Types and Operations

COMP 202 Java in one week

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

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

Datatypes, Variables, and Operations

Chapter. Let's explore some other fundamental programming concepts

3. Java - Language Constructs I

JAVA Ch. 4. Variables and Constants Lawrenceville Press

ECE 122 Engineering Problem Solving with Java

Information Science 1

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

Important Java terminology

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

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

Tutorial 03. Exercise 1: CSC111 Computer Programming I

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

Programming with Java

Program Fundamentals

CS313D: ADVANCED PROGRAMMING LANGUAGE

Information Science 1

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Chapter 2: Data and Expressions

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Chapter 2: Data and Expressions

Elementary Programming

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

Full file at

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CSC 1214: Object-Oriented Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

2 rd class Department of Programming. OOP with Java Programming

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

Data Conversion & Scanner Class

Primitive Data Types: Intro

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

Chapter 2 Primitive Data Types and Operations

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Computational Expression

CS110: PROGRAMMING LANGUAGE I

Accelerating Information Technology Innovation

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

3. Java - Language Constructs I

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

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

Chapter 2: Data and Expressions

COMP 202 Java in one week

More Programming Constructs -- Introduction

Eng. Mohammed S. Abdualal

Welcome to the Primitives and Expressions Lab!

Declaration and Memory

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

Zheng-Liang Lu Java Programming 45 / 79

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

COMP 202. Java in one week

DM550 Introduction to Programming part 2. Jan Baumbach.

CS111: PROGRAMMING LANGUAGE II

2: Basics of Java Programming

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Primitive Data, Variables, and Expressions; Simple Conditional Execution

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Computer System and programming in C

Chapter 2. Elementary Programming. Program Listings

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

Programming Lecture 3

Fundamentals of Programming Data Types & Methods

Computational Expression

Lecture Set 2: Starting Java

Basic Programming Elements

CIS133J. Working with Numbers in Java

Lecture Set 2: Starting Java

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Introduction to C# Applications

Fundamentals of Programming Session 7

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

Transcription:

Chapter 2 Elementary Programming 1

Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants, methods, and classes To use variables to store data To program with assignment statements and assignment expressions To use constants to store permanent data To declare Java primitive data types: byte, short, int, long, float, double, boolean, and char To use Java operators to write numeric expressions To cast value of one type to another type To know common errors in Java 2

Introducing Programming with an Example Listing 2.1, page 35: Computing the Area of a Circle This program computes the area of the circle. 3

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20.0; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } radius allocate memory for radius no value 4

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20.0; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } radius area memory no value no value allocate memory for area 5

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20.0; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } radius area assign 20 to radius 20.0 no value 6

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20.0; radius area memory 20.0 1256.636 // Compute area area = radius * radius * 3.14159; compute area and assign it to variable area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 7

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20.0; radius area memory 20.0 1256.636 // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } print a message to the console 8

Reading Input from the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the methods next(), nextbyte(), nextshort(), nextint(), nextlong(), nextfloat(), nextdouble(), or nextboolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, Scanner input = new Scanner(System.in); System.out.print("Enter a double value: "); double doublevalue = input.nextdouble(); 9

Example 1 // Scanner is stored in java.util package import java.util.scanner; public class ComputeAreaWithCnsoleInput { public static void main(string[] args) { //create a Scanner object Scanner input = new Scanner(System.in); //Prompt the user to enter a radius System.out.print("Enter a number for radius (double): "); double radius = input.nextdouble(); //Compute area double area = radius * radius * 3.14159; } //Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 10

Example 2 // Scanner is stored in java.util package import java.util.scanner; public class ComputeAverage { public static void main(string[] args) { // create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter three numbers System.out.print("Enter three numbers (type double): "); double number1 = input.nextdouble(); double number2 = input.nextdouble(); double number3 = input.nextdouble(); // Compute average double average = (number1 + number2 + number3) / 3.0; } } // Display results System.out.println("The average of " + number1 + " " + number2 + " " + number3 + " is " + average); 11

Identifiers Identifier is a name for an element in the program, such as variable, class, and method. An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identifier cannot be a reserved word. (Java Keywords). An identifier can be of any length. 12

13 Reserved Words Java reserved words: abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while

Variable Declaration A variable is a name for a location in memory to store data of specific type. A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration 14

Variable Initialization A variable can be given an initial value in the declaration. // declare and initialize int sum; sum = 0; int base = 32; double max = 149.75; When a variable is referenced in a program, its current value is used. 15

Examples // Compute the area double radius; // declaration double area; // declaration radius = 1.0; // initialization area = radius * radius * 3.14159; System.out.println("The area is + area + " for radius "+radius); // Compute the area double radius = 2.0;// declaration and initialization double area = radius * radius * 3.14159; //same here System.out.println("The area is + area + " for radius "+radius); 16

More Variables Must declare all variables to let the program know what to store in the variables. int grade; // Declare grade as integer variable double radius; // Declare radius as double variable float speed; // Declare speed as float variable char letter; // Declare letter as character variable boolean flag; // Declare flag as boolean variable short price; // Declare price as short variable long quantity; // Declare quantity as long variable 17

Variable Initialization Example // Prints the number of keys on a piano. public class PianoKeys { public static void main (String[] args) { int keys = 88; //declare and initialize System.out.println ("A piano has " + keys + " keys."); } } Output: A piano has 88 keys. 18

Declaring and Initializing in One Step int x = 1; double d = 1.4; Same as: int x; x = 1; double d; d = 1.4; 19

Assignment An assignment statement changes the value of a variable The assignment operator is the = sign int total; total = 55; The expression on the right is evaluated and its result is stored in the variable on the left. The value that was in total is overwritten. You can only assign a value to a variable that is consistent with the variable's declared type. See program Geometry.java next slide. 20

Assignment - Example // Print the number of sides of several geometric shapes. public class Geometry { public static void main (String[] args) { int sides = 7; // declare and initialize System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); } sides = 12; // assignment statement System.out.println ("A dodecagon has " + sides + " sides."); } 21

Assignment Statement Examples classsize = 40; // Assign 40 to classsize radius = 3.0; // Assign 3.0 to radius letter = 'A'; // Assign 'A' to letter answer = true; // Assign true to answer //compute and assign to circulearea circlearea = radius * radius * Math.PI; 22

Constants A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant, not variable. The compiler will issue an error if you try to change the value of a constant. In Java, we use the final modifier to declare a constant, such as: final int MIN_HEIGHT = 69; final boolean DEFAULT_ANSWER = true; 23

Constants Constants are useful for three important reasons: - First, they give meaning to otherwise unclear literal (numeric) values. - Second, they facilitate program maintenance so you make the value change in one place. - Third, they help avoid inadvertent errors by other programmers. 24

Constants - Examples Format: final datatype CONSTANT_NAME = Value; Examples: final int CLASS_SIZE = 40; final double MATH_PI = 3.14159; final char FAIL_GRADE = 'F'; final boolean FLAG = true; 25

Primitive Data Types There are eight primitive data types in Java: Four of them represent integer numbers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean Everything else in Java is of type object. 26

Sizes of Primitive Numeric Types byte short int long 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits float 8 bits 8 bits 8 bits 8 bits double 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits 8 bits char 8 bits 8 bits boolean 8 bits 8 bits 8 bits 8 bits 27

Values of Primitive Numeric Types The difference between the various numeric primitive types is their memory size: Type Storage Min Value Max Value byte short int long 8 bits 16 bits 32 bits 64 bits -128-32,768-2,147,483,648 < -9 x 10 18 127 32,767 2,147,483,647 > 9 x 10 18 float Double boolean 32 bits 64 bits 32 bits +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits Either true or false 28

Numeric Operators Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2 29

Integer Division and Remainder 5 / 2 yields an integer 2 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (remainder value) Note 5 / 2.0 OR 5.0 / 2 ==> 2.5 30

Remainder Operator - Example Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday. You and your friends are going to meet in 10 days from today. What day is would that be? You can find that out using the following expression: Saturday is the 6 th day in a week (6 + 10) % 7 is 2 After 10 days A week has 7 days The 2 nd day in a week is Tuesday 31

Number Literals A literal is a constant value that appears directly in the program. For example, 40, 1000000, 5.0, true, and A are literals in the following statements: int classsize = 40; long largenumber = 1000000; double increment = 5.0; boolean defaultanswer = true; char lettergrade = 'A'; 32

Arithmetic Expressions 3 + 4x 10( y 5)( a + b + c) 4 9 + + 9( + 5 x x y x ) is translated to (3+4*x)/5 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 33

How to Evaluate an Expression Java uses arithmetic precedence rule for evaluating expression. 3 + 4 * 4 + 5 * (4 + 3) - 1 (1) inside parentheses first 3 + 4 * 4 + 5 * 7 1 (2) multiplication 3 + 16 + 5 * 7 1 (3) multiplication 3 + 16 + 35 1 (4) addition 19 + 35 1 (5) addition 54-1 (6) subtraction 53 34

How to Evaluate an Expression What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 35

Problem: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula: celsius 5 = ( 9 )( fahrenheit 32) Double celsius = (5.0/9.0) * (fahrenheit - 32); Homework: Type, compile and execute the program in listing 6, page 51. 36

Problem: Displaying Current Time Write a program that displays current time in GMT in the format hour:minute:second such as 1:45:19. The currenttimemillis method in the System class returns the current time in milliseconds since the midnight, January 1, 1970 GMT. (1970 was the year when the Unix operating system was formally introduced.) You can use this method to obtain the current time, and then compute the current second, minute, and hour as follows. Homework: Type, compile and execute the program in listing 7, page 52. Notice the use of the division(/) and remainder (%) operators. 37

Shortcut Assignment Operators Operator Example Equivalent (recommended use) += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8 38

Increment and Decrement Operators Operator Name Description ++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1. 39

Increment and Decrement Operators, cont. int i = 10; Same effect as int newnum = 10 * i++; int newnum = 10 * i; i = i + 1; int i = 10; Same effect as int newnum = 10 * (++i); i = i + 1; int newnum = 10 * i; 40

Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int i = 10; int k = ++i + i; Output: i = 11 k = 22 41

Type Conversion Conversions must be handled carefully to avoid losing information. Widening conversions are safest because they tend to go from a small data type to a larger one (such as short to int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as int to short) In Java, data conversions can occur in three ways: - assignment conversion - promotion (temporary conversion) - casting (explicit conversion) 42

Assignment Conversion Assignment conversion occurs when a value of one type is assigned to a variable of another If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float. double money = 0.0; int dollars = 10; money = dollars; // money has value 10.0 dollars = money; // ERROR!!!! Only widening conversion can happen via assignment. Note that the value or type of dollars did not change. 43

Promotion Conversion Promotion happens automatically (and temporarily) when operators in expressions convert their operands. Example : int count = 5; double sum = 20.0; double result; result = sum/count; //result contains 4.0 result = count/sum; //result contains 0.25 The value of count is temporarily promoted (converted) to a floating point value to perform the calculation. count is still of type integer. 44

Casting Conversion Casting is the most powerful, and dangerous, technique for conversion. Both widening and narrowing conversions can be accomplished by explicit casting. To cast, the type name is put in parentheses in front of the value being converted. Example int total = 20, count = 5; double result1, result2;... result1 = (float)total/count; //casting and promotion result2 = (float)(total/count); //casting only 45

Casting Conversion How do we solve the problem of 3 / 2 having a result of 1. You can make one of the values floating point by adding.0 to it (conversion by promotion) 3.0 / 2 3 / 2.0 The result type will then be floating point value (1.5) Or You can cast one of the values to either float or double (conversion by casting) (double) 3 / 2 3 / (float) 2 46

Conversion Rules When performing an operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. 47

Type Casting Examples Implicit casting double d = 3; //type widening with assignment Explicit casting int i = (int)3.0; //explicit type narrowing int i = (int)3.9; //fraction part is truncated What is wrong here? int x = 5 / 2.0; //syntax error range increases byte, short, int, long, float, double 48

Software Development Process 49

Software Development Process In this course, you need to start with: 1. Understand the problem. 2. Identify what the input and outputs. 3. Decide how to process the inputs to produce the outputs (algorithm). 4. Write down the logical steps of the algorithm. 5. Translate the algorithmic steps into Java code. 6. Type code, compile, fix errors, run, and test the program for correctness of outputs. 50

Problem: Monetary Units This program allows the user to enter the amount representing dollars and cents (in decimal) and output a report listing the monetary equivalence in coins (dollars, quarters, dimes, nickels, and pennies). The program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. 51

Development steps: Problem: Monetary Units 1. Understand the problem: The program reads an amount of money such as $1.41 and prints out the change. 2. Ask the user to enter an amount (of type double). 3. Convert the amount to pennies (cents) (easier to work with integer type). Use casting to convert double type to int type. 3. Divide the amount by 100 to get # of dollar coins (using / operator). 4. Determine the remaining change (use remainder operator %). 5. Repeat steps 3 and 4 to get the quarters, dimes, and nickels. 6. The final remaining change amount is the number of pennies. 7. Display the outputs with proper labels. 52

Problem: Monetary Units import java.util.scanner; public class ComputeChange { public static void main(string[] args) { // Create a Scanner // Read amount from user (double, e.g., 2.37) // Convert input amount to cents (int, e.g., 237) // Other code // Find the number of one dollars int numberofonedollars = remainingamount / 100; remainingamount = remainingamount % 100; // Find the number of quarters in the remaining amount int numberofquarters = remainingamount / 25; remainingamount = remainingamount % 25; // Other code... // Display results System.out.println("Your amount " + amount + " consists of"); System.out.println(" " + numberofonedollars + " dollars");... } } //See listing 2.10, page 63 for complete code 53

Common Errors Common Error 1: Undeclared/Uninitialized Variables and Unused Variables Common Error 2: Overflow Errors Example: byte x = 127; //max byte value x = x + 5; //causes overflow Common Error 3: Round-off Errors Example: double x= 1.0-0.9 //expect 0.1 // output is 0.0999999999 54

Common Errors Common Error 4: Unintended Integer Division Example: int Celsius = 40; int Fahrenheit = (int)((5/9) * Celsius + 32); //output is always 32!!! Common Error 5: Redundant Input Objects (such as creating a scanner object for each input variable or each type!) See textbook, page 66, for examples. 55

End of Chapter 2 56