Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can.

Slides:



Advertisements
Similar presentations
Logic & program control part 2: Simple selection structures.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Types and Arithmetic Operators
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
Introduction to C Programming
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
Expressions, Data Conversion, and Input
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
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
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CPS120: Introduction to Computer Science
Flow of Control Part 1: Selection
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Introduction to Java Java Translation Program Structure
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
ICT Introduction to Programming Chapter 4 – Control Structures I.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
The Math Class Methods Utilizing the Important Math Operations of Java!
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
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.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Lesson 4: Introduction to Control Statements 4.1 Additional Operators Extended Assignment Operators –The assignment operator can be combined with the.
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.
CompSci 230 S Programming Techniques
Expressions.
Data Types and Expressions
Lecture 3 Java Operators.
Selections Java.
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Basic Elements of Java
Expressions and Assignment
Unit 3: Variables in Java
Chapter 2 Primitive Data Types and Operations
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

Numeric Values and Computations Today, we extend our programming capabilities by adding numeric values and computations –As introduced last time, we can store numeric values in int and double variables int x; double y; –In order to use these values, we write expressions which are much like mathematical expressions like x + 5 or y * 1.1 –We store the results in other variables using assignment statement

Assignment Statements The assignment statement assigns a variable to a value –variable = expression variable is some variable previously declared expression is some arithmetic expression using variables, literals, and arithmetic operators +, -, *, /, % (mod) For an assignment statement to properly work, the expression must compute the same (or a compatible) type as the type that the variable was declared as –x = 5 * y – z; // x must be a compatible type with y and z Compatibility – same type or a type that can be adapted into another –an int value can become a double or float –a float can become a double –a double cannot become a float or int

Assignment Statement Examples To compute an employee’s pay: pay = wages * hours; To compute the area of a circle: area = PI * radius * radius; Orarea = PI * Math.pow(radius, 2); To compute the average of 5 test scores: average = (t1 + t2 + t3 + t4 + t5) / 5; Note that if t1, t2, t3, t4 and t5 are int values, the expression computes an integer value (an int numerator and an int denominator cause an int division, not a float or double division) Math is another class, we use it to peform various math operations like absolute value, or exponent

More on Assignments Expressions may also contain messages to various objects as long as the messages invoke operations that return the proper type of value –for instance, the Math class has a number of such operations such as sqrt or abs x = z * Math.sqrt(y);// what if y is negative? x = z * Math.sqrt(Math.abs(y)); x = Math.random( ); // x is a random integer value –int values range from about -2 billion to +2 billion, this gives us a random one in that range –or the String length message: nameLength = firstName( ).length + middleName( ).length + lastName( ).length;

The Modulo (Mod) Operator A common need in a program is to perform a division but obtain the remainder instead of the quotient –For instance, is x an even number? We determine this by dividing x by 2 and looking at the remainder a remainder of 0 means x is even and a remainder of 1 means x is odd –The mod operator is % x % 2 will be 0 or 1 (the only remainder for x / 2 is a 0 or a 1) Assume we want to use the random number generator to give us a roll of a 6-sided die –Math.abs(Math.random( )) % 6 divide positive int value by 6 and provide just the remainder (0 to 5) –Math.abs(Math.random( )) % gives us a number between 1 and 6

More Examples Volume of a cube: volume = length * length * length; Number of seconds in x years: seconds = x * 365 * 24 * 60 * 60; // whats wrong with the above example? Convert F to C: celcius = (5.0 / 9) * (fahrenheit – 32); celcius = ((double) 5) / 9 * (fahrenheit – 32); Determining change (assume amount in cents as in 142 cents) numQuarters = amount / 25; //int division gives 5 quarters amount = amount % 25; //remainder is 17 numDimes = amount / 10; //gives 1 dime amount = amount % 10; //remainder is 7 numNickels = amount / 5; //gives 1 nickel amount = amount % 5; //remainder is 2 pennies numPennies = amount;

Short Cuts There are certain types of assignment statements that are used so often that we given them special shortcuts –Recall earlier the “making change” example where we saw amount = amount – numQuarters * 25; –In general, we might have a statement that looks like this: var = var op expression (where op is one of our arithmetic operators) –We can replace this with var op= expression amount –= numQuarters * 25; –The statement x = x + y * z / q; becomes x += y * z / q; –Another very common statement is to increment or decrement a variable (add 1 or subtract 1) usually, this looks like: x = x + 1; or count = count – 1; –We replace these with x++; and count--;

More on Increment/Decrement There are two versions of each statement, a prefix statement and a postfix statement x = x + 1; can be done as x++; or ++x; (or x + =1;) x = x – 1; can be done as x--; or --x; (or x -= 1;) –x++;x--;++x;--x; If the incr/decr is by itself, it doesn’t matter which you use, but these can appear inside of other expressions –x++ will use the value of x first, and then increment it (postfix) whereas ++x will increment x first and then use the new value (prefix) –y = 5 * x++; this does y = 5 * x; and then does x = x + 1; if x = 3, then when the statement is done, y = 15 and x = 4 –y = 5 * ++x; this does x = x + 1; first and then y = 5 * x; if x = 3, then when the statement is done, y = 20 and x = 4

Numeric Conversions Two types of conversion processes in Java –Implicit conversions (called coercions) occur automatically if the left-hand side variable is a different type as to the right-hand side expression x = y;// y is an int, x is a double –Casts occur because you force a value to change types casts are performed by placing the new type in ( ) as in (int) average = ((double) t1 + t2 + t3 + t4 + t5) / 5; changes t1 to a double, then the rest of the expression computes a double value not an int value –we could force a coercion instead by doing average = (t1 + t2 + t3 + t4 + t5) / 5.0; // 5.0 is a double, so the entire thing becomes a double

Converting Inputs The JOptionPane.showInputDialog message inputs Strings only, we have to convert the String to another form –To convert an input into an int use: Integer.parseInt(JOptionPane.showInputDialog(…)); int age = Integer.parseInt(JOptionPane.showInputDialog(“Enter your age”)); –To convert an input into a double use: Double.parseDouble(JOptionPane.showInputDialog(…)); double gpa = double.parseDouble(JOptionPane.showInputDialog(“Enter your GPA”)); –To convert an input into a char use: JOptionPane.showInputDialog(…).charAt(0); char sex = JOptionPane.showInputDialog(“Enter your sex”).charAt(0); We prefer to use the Scanner which has next( ) for String input, nextInt( ) and nextDouble( ) –For characters, we still need to use.charAt(0)

Control Statements There are generally four types of executable instructions in a program: –Assignment statements –Input/output statements –Messages (method calls) –Control statements In a program, all instructions are executed linearly (sequentially) –Unless a control statement alters the flow of the program There are 2 types of control statements –Selection –Repetition (also called iteration or loops)

Branching Behavior Sequential instruction Branching instruction Sequential instruction Branching instruction Sequential instruction Branching instruction Sequential instruction … Ordinarily, the program is executed by following each sequential instruction in order A control statement causes a “branch” to a new location Branches may be used to select between instructions, to skip over instructions, or to repeat instructions ?

Selection Selection statements are used to skip an instruction or to choose among a set of instructions The selection is based on a boolean evaluation –Booleans evaluate to true or false if true, do the statement(s), if false, skip the statement(s) the boolean evaluation can be based on a boolean variable or a boolean expression –In this way, given 1 or more statements, the boolean expression is used to determine which one to select and execute

Boolean Expressions A Boolean expression is code that evaluates to true or false Boolean expressions often use relational operators to test the value of a variable or to compare two or more variables There are 6 relational operators: –< less than –> greater than –= = equal to notice it is not the same as “=” used in assignment statements –! = not equal to –< = less than or equal to –> = greater than or equal to Variables and values tested using relational operators can be of numeric types or char types, we will also see ways to compare String types

The if Statement if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped. A common form of selection statement is the if statement In the if statement, a condition is tested, and if it evaluates to true then the statement which follows is executed, otherwise the statement which follows is skipped condition evaluated false statement true

Examples if (total > amount) total = total + (amount + 1); if (sex = = ‘m’) pay = pay + 500; if (age > 21) System.out.println( " Ok, you can drink " ); if (sunny) System.out.println( " Wear your sunglasses! " ); if (rainy) System.out.println( " Take an umbrella " ); if (x > y) x = x * 5 + y; sex is a character sunny and rainy are Boolean variables Warning: Do not confuse = and = =

A Few Comments The statement starts with if (not IF, If or iF) The boolean condition must be placed within ( ) The condition itself is not followed by a “;” –For instance, the following statement would confuse the compiler into thinking that the instruction to execute for the if statement is ; and that x = y + 1; is the next instruction in the program if (x > y); x = y + 1; We may couple the if statements with an “else” clause –in case there is an action to perform if the condition is false –this is known as an if-else statement (or if-then-else)

if-else statement Used if there are two possibilities –if you want to calculate someone’s pay, there are two formulas, one for normal pay and another for overtime pay example below to the right The if-else statement has two separate statements, one following the condition, one following the word else –neither the condition nor else have a “;” after it, the “;” follows the statement we refer to the statements as they “if clause” and the “else clause” condition evaluated statement1 truefalse statement2 if (hours <= 40) pay = hours * wages; else pay = 40 * wages + (hours – 40) * wages * 1.5;

More Examples if (score > 60) grade = ‘P’; else grade = ‘F’; if (number >= 0) sqt = Math.sqrt(number); else System.out.println( " Can’t take the square root of a negative number! " ); if (number = = 0) System.out.println( " Can’t take reciprocal of 0 " ); else rec = 1.0 / (float) number; if (age >= 21) canGamble = true; else canGamble = false; Use if-else to decide what value should be assigned a variable Use if-else to decide if an operation could/should be performed

String Comparisons Comparing Strings is not like comparing other values If a and b are Strings, then this does not work: if(a = = b) …; –This compares to see if a and b are the same thing in memory, not just two equal Strings To see if two String variables are storing the same values, use equals –if(a.equals(b))…; –if(a.equalsIngoreCase(b)) …; // if we don’t care about upper vs lower case We may want to see what the user has entered to see if they followed directions –for instance, we want the user to enter their name or quit to exit the program if(value.equal(“quit”)) System.exit(0); –this only works if they type in exactly “quit”, what if they typed “Quit”? if(value.equalIgnoreCase(“quit”)) System.exit(0); –what if they typed “q” or “Q”? if(value.toLowerCase( ).charAt(0) = = ‘q’) System.exit(0);

Another String Comparison When it comes to sorting Strings, we will want to know if one String is than another –We use compareTo for this –compareTo returns an int value negative if the first String is less than the second 0 if the first String is equal to the second positive if the first String is greater than the second if (a.compareTo(b) > 0) System.out.println(a + “ is greater than ” + b); else if (a.compareTo(b) < 0) System.out.println(b + “ is greater than ” + a); else System.out.println(a + “ is the same as ” + b);

Block Statements Notice that in all of our previous examples, the statement in the if clause and the else clause consisted of a single instruction What if we needed to accomplish more than one instruction in an if or else clause? –we use block statements –a block is a sequence of statements that is treated like a single statement when placed in an if or else clause Blocks are denoted by { } symbols –{ is the beginning of a block, } is the ending of a block Blocks will be used often in our Java programs

Example if (temperature > 80) { System.out.print( " Wear shorts and t-shirt " ); effectiveTemp = temperature + HEATINDEX * humidity; System.out.println( " because it is " + effectiveTemp + " degrees today " ); } else System.out.println( " It is not hot today, the temperature is " + temperature); The if-clause has 3 instructions, so we place them in a block If we didn’t use a block, then we would get a syntax error because the compiler would get confused when it reached the “else” since it did not immediately follow the if-clause