Expressions Eric Roberts CS 106A January 13, 2016.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.2 Expressions and Assignment Statement.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
Introduction to C Programming
Expressions Java 3.1 Primitive data types 3.2 Constants and variables
Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements.
Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Objectives You should be able to describe: Data Types
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
EXPRESSIONS AND ASSIGNMENT CITS1001. Scope of this lecture Assignment statements Expressions 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
Chapter 3—Expressions The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Expressions C H A P T E R 3 “ What ’ s twice eleven?
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Chapter 4—Statement Forms The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Statement Forms C H A P T E R 4 The statements.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
COMP Primitive and Class Types Yi Hong May 14, 2015.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Chapter 4 Statement Forms. Statement types 1.Simple statements expression; println(“The total is “ + total + “.”); (method call) 2. Compound statements.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
 Most C programs perform calculations using the C arithmetic operators (Fig. 2.9).  Note the use of various special symbols not used in algebra.  The.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
Five-Minute Review 1.What are classes and objects? What is a class hierarchy? 2.What is an expression? A term? 3.What is a variable declaration? 4.What.
Programming – Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in 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.
Eric Roberts and Jerry Cain
CS 106A, Lecture 4 Introduction to Java
Simple JavaScript Eric Roberts CS 106J April 10, 2017.
2.5 Another Java Application: Adding Integers
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
JavaScript: Control Statements I
Java Programming: From Problem Analysis to Program Design, 4e
INPUT & OUTPUT scanf & printf.
Introduction to C++ Programming
slides courtesy of Eric Roberts
Expressions and Assignment
Expressions Java 3.1 Primitive data types 3.2 Constants and variables
Chapter 2 Programming Basics.
Primitive Types and Expressions
Using C++ Arithmetic Operators and Control Structures
Chapter 4—Statement Forms
Presentation transcript:

Expressions Eric Roberts CS 106A January 13, 2016

Once upon a time...

Holism vs. Reductionism In his Pulitzer-prizewinning book, computer scientist Douglas Hofstadter identifies two concepts—holism and reductionism—that turn out to be important as you begin to learn about programming. Hofstadter explains these concepts using a dialogue in the style of Lewis Carroll: I will be glad to indulge both of you, if you will first oblige me, by telling me the meaning of these strange expressions, “holism” and “reductionism”. Achilles: Crab: Holism is the most natural thing in the world to grasp. It’s simply the belief that “the whole is greater than the sum of its parts”. No one in his right mind could reject holism. Anteater: Reductionism is the most natural thing in the world to grasp. It’s simply the belief that “a whole can be understood completely if you understand its parts, and the nature of their ‘sum’”. No one in her left brain could reject reductionism.

Expressions

The Add2Integers Program Add2Integers class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } n1n2total This program adds two numbers. Enter n2: The total is class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } n1n2total Enter n1: 17

Expressions in Java The heart of the Add2Integers program from Chapter 2 is the line The n1 + n2 that appears to the right of the equal sign is an example of an expression, which specifies the operations involved in the computation. An expression in Java consists of terms joined together by operators. Each term must be one of the following: –A constant (such as or "hello, world" ) –A variable name (such as n1, n2, or total ) –A method call that returns a value (such as readInt ) –An expression enclosed in parentheses int total = n1 + n2; that performs the actual addition.

Primitive Data Types Although complex data values are represented using objects, Java defines a set of primitive types to represent simple data. Of the eight primitive types available in Java, the programs in this text use only the following four: int This type is used to represent integers, which are whole numbers such as 17 or – 53. double This type is used to represent numbers that include a decimal fraction, such as char This type represents a single character. boolean This type represents a logical value ( true or false ).

Constants and Variables The simplest terms that appear in expressions are constants and variables. The value of a constant does not change during the course of a program. A variable is a placeholder for a value that can be updated as the program runs. The format of a constant depends on its type: –Integral constants consist of a string of digits, optionally preceded by a minus sign, as in 0, 42, -1, or –Floating-point constants include a decimal point, as in or Floating-point constants can also be expressed in scientific notation by adding the letter E and an exponent after the digits of the number, so that 5.646E-8 represents the number x –The two constants of type boolean are true and false. –Character and string constants are discussed in detail in Chapter 8. For the moment, all you need to know is that a string constant consists of a sequence of characters enclosed in double quotation marks, such as "hello, world". A variable in Java is most easily envisioned as a box capable of storing a value. Each variable has the following attributes: –A name, which enables you to differentiate one variable from another. –A type, which specifies what type of value the variable can contain. –A value, which represents the current contents of the variable. total (contains an int ) 42 The name and type of a variable are fixed. The value changes whenever you assign a new value to the variable.

Variable Declarations In Java, you must declare a variable before you can use it. The declaration establishes the name and type of the variable and, in most cases, specifies the initial value as well. type name = value ; The most common form of a variable declaration is where type is the name of a Java primitive type or class, name is an identifier that indicates the name of the variable, and value is an expression specifying the initial value. Most declarations appear as statements in the body of a method definition. Variables declared in this way are called local variables and are accessible only inside that method. Variables may also be declared as part of a class. These are called instance variables and are covered in Chapter 6.

Operators and Operands As in most languages, Java programs specify computation in the form of arithmetic expressions that closely resemble expressions in mathematics. The most common operators in Java are the ones that specify arithmetic computation: + Addition – Subtraction * Multiplication / Division % Remainder Operators in Java usually appear between two subexpressions, which are called its operands. Operators that take two operands are called binary operators. The - operator can also appear as a unary operator, as in the expression -x, which denotes the negative of x.

Division and Type Casts Whenever you apply a binary operator to numeric values in Java, the result will be of type int if both operands are of type int, but will be a double if either operand is a double. This rule has important consequences in the case of division. For example, the expression 14 / 5 seems as if it should have the value 2.8, but because both operands are of type int, Java computes an integer result by throwing away the fractional part. The result is therefore 2. If you want to obtain the mathematically correct result, you need to convert at least one operand to a double, as in (double) 14 / 5 The conversion is accomplished by means of a type cast, which consists of a type name in parentheses.

9 / 5 * c + 32 The Pitfalls of Integer Division Consider the following Java statements, which are intended to convert 100˚ Celsius temperature to its Fahrenheit equivalent: double c = 100; double f = 9 / 5 * c + 32; The computation consists of evaluating the following expression: The problem arises from the fact that both 9 and 5 are of type int, which means that the result is also an int. 9 / 5 * c

The Pitfalls of Integer Division You can fix this problem by converting the fraction to a double, either by inserting decimal points or by using a type cast: double c = 100; double f = (double) 9 / 5 * c + 32; The computation now looks like this: (double) 9 / 5 * c

The Remainder Operator The result of the % operator make intuitive sense only if both operands are positive. The examples in the book do not depend on knowing how % works with negative numbers. The remainder operator turns out to be useful in a surprising number of programming applications and is well worth a bit of study. The only arithmetic operator that has no direct mathematical counterpart is %, which applies only to integer operands and computes the remainder when the first divided by the second: 14 % 5 returns 4 14 % 7 returns 0 7 % 14 returns 7

Precedence If an expression contains more than one operator, Java uses precedence rules to determine the order of evaluation. The arithmetic operators have the following relative precedence: unary - ( type cast ) * / % + - highest lowest Thus, Java evaluates unary - operators and type casts first, then the operators *, /, and %, and then the operators + and -. Precedence applies only when two operands compete for the same operator. If the operators are independent, Java evaluates expressions from left to right. Parentheses may be used to change the order of operations.

( Exercise: Precedence Evaluation What is the value of the expression at the bottom of the screen? 1+2)%3*4+5*6/7*(8%9)

Assignment Statements variable = expression ; You can change the value of a variable in your program by using an assignment statement, which has the general form: The effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left. Thus, the assignment statement total = total + value; adds together the current values of the variables total and value and then stores that sum back in the variable total. When you assign a new value to a variable, the old value of that variable is lost.

Shorthand Assignments Statements such as total = total + value; are so common that Java allows the following shorthand form: total += value; variable op = expression ; The general form of a shorthand assignment is where op is any of Java’s binary operators. The effect of this statement is the same as variable = variable op ( expression ); For example, the following statement multiplies salary by 2. salary *= 2;

Increment and Decrement Operators Another important shorthand form that appears frequently in Java programs is the increment operator, which is most commonly written immediately after a variable, like this: x++; The effect of this statement is to add one to the value of x, which means that this statement is equivalent to x += 1; or in an even longer form x = x + 1; The -- operator (which is called the decrement operator) is similar but subtracts one instead of adding one. The ++ and -- operators are more complicated than shown here, but it makes sense to defer the details until Chapter 11.

Extending Add2Integers The next few slides extend the Add2Integers program from Chapter 2 to create programs that add longer lists of integers. These slides illustrate three different strategies: –Adding new code to process each input value –Repeating the input cycle a predetermined number of times –Repeating the input cycle until the user enters a sentinel value

The Add4Integers Program public class Add4Integers extends ConsoleProgram { public void run() { println("This program adds four numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int n3 = readInt("Enter n3: "); int n4 = readInt("Enter n4: "); int total = n1 + n2 + n3 + n4; println("The total is " + total + "."); } You could easily change the Add2Integers into a program that added four integers just by adding additional variables, as shown in the following example: This strategy, however, is difficult to generalize and would clearly be cumbersome if you needed to add 100 values.

The Repeat-N-Times Pattern One strategy for generalizing the addition program is to use the Repeat-N-Times pattern, which executes a set of statements a specified number of times. The general form of the pattern is for (int i = 0; i < repetitions ; i++) { statements to be repeated } As is true for all patternatic patterns in this book, the italicized words indicate the parts of the pattern you need to change for each application. To use this pattern, for example, you need to replace repetitions with an expression giving the number of repetitions and include the statements to be repeated inside the curly braces. The information about the number of repetitions is specified by the first line in the pattern, which is called the header line. The statements to be repeated are called the body of the for statement and are indented with respect to the header line. A control statement that repeats a section of code is called a loop. Each execution of the body of a loop is called a cycle. for (int i = 0; i < repetitions ; i++) { statements to be repeated }

The AddNIntegers Program public class AddNIntegers extends ConsoleProgram { public void run() { println("This program adds " + N + " numbers."); int total = 0; for (int i = 0; i < N; i++) { int value = readInt(" ? "); total += value; } println("The total is " + total + "."); } private static final int N = 100; } This program uses the Repeat-N-Times pattern to compute the sum of a predetermined number of integer values, specified by the named constant N. The for loop in this example works correctly only if the variable total is initialized to 0 before executing the loop. This body of the loop consists of two statements. The first reads an integer from the user into the variable value, and the second adds that value to the variable total. This program uses the Repeat-N-Times pattern to compute the sum of a predetermined number of integer values, specified by the named constant N. public class AddNIntegers extends ConsoleProgram { public void run() { println("This program adds " + N + " numbers."); int total = 0; for (int i = 0; i < N; i++) { int value = readInt(" ? "); total += value; } println("The total is " + total + "."); } private static final int N = 100; }

The Repeat-Until-Sentinel Pattern A better approach for the addition program that works for any number of values is to use the Repeat-Until-Sentinel pattern, which executes a set of statements until the user enters a specific value called a sentinel to signal the end of the list: while (true) { prompt user and read in a value if (value == sentinel ) break; rest of loop body } You should choose a sentinel value that is not likely to occur in the input data. It also makes sense to define the sentinel as a named constant to make the sentinel value easy to change.

The AddIntegerList Program public class AddIntegerList extends ConsoleProgram { public void run() { println("This program adds a list of integers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; } println("The total is " + total + "."); } private static final int SENTINEL = 0; } This program uses the Repeat-Until-Sentinel pattern to add a list of integers, stopping when the user enters a value that matches the named constant SENTINEL.

The AddIntegerList Program public void run() { println("This program adds a list of integers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; } println("The total is " + total + "."); } AddIntegerList valuetotal This program adds a list of integers. The total is 6. ? 1 to signal the end of the list. ? 2 ? 3 ? 0 Enter values, one per line, using public void run() { println("This program adds a list of integers."); println("Enter values, one per line, using " + SENTINEL); println("to signal the end of the list."); int total = 0; while (true) { int value = readInt(" ? "); if (value == SENTINEL) break; total += value; } println("The total is " + total + "."); } valuetotal 60 skip simulation

The End