Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax = 0.085.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

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.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
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.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Expressions, Data Conversion, and Input
Copyright © 2003 Pearson Education, Inc. Slide 2-1 Problem Solving with Java™ Second Edition Elliot Koffman and Ursula Wolz Copyright © 2003 Pearson Education,
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
Ryan Chu. Arithmetic Expressions Arithmetic expressions consist of operators, operands, parentheses, and function calls. The purpose is to specify an.
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 2 part #4 Operator
Object-Oriented Programming Using C++ Third Edition Chapter 2 Evaluating C++ Expressions.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
LESSON 6 – Arithmetic Operators
CHAPTER 2 PART #4 OPERATOR 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101 By: Asma Alosaimi Edited.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2: Using Data.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To be able to list and describe the six expression categories ❏ To understand.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Integer numerical data types. The integer data types The integer data types use the binary number system as encoding method There are a number of different.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Arithmetic Expressions in C++. CSCE 1062 Outline Data declaration {section 2.3} Arithmetic operators in C++ {section 2.6} Mixed data type arithmetic in.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Operators & Expressions
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.
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.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
 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.
1 Chapter 3 – Operators and Expressions Outline 3.1Introduction 3.2Arithmetic operators 3.3Relational operators 3.4Logical operators 3.5Assignment operators.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
CSE 220 – C Programming Expressions.
Lecture 3 Java Operators.
Side Effect Operators Changing the value of variables
Relational Operations
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Operators and Expressions
Arithmetic Operator Operation Example + addition x + y
Conversions of the type of the value of an expression
Structure of a C Program
Lecture 3 Expressions Richard Gesick.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
A First Book of ANSI C Fourth Edition
C Operators, Operands, Expressions & Statements
Chapter-3 Operators.
Associativity and Prescedence
Chapter 3 Operators and Expressions
Data Types and Expressions
Chapter 4: Expression and Operator
OPERATORS AND EXPRESSIONS IN C++
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Operator King Saud University
Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a language-specific syntactical token.
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax = * totalSale Need to specify what operations are legal, how operators evaluated, etc. C operations are referred to as Expressions

Outline II. Program Basics G. Expressions 1. Primary identifiers, constants, parenthesized expressions 2. Unary postfix: function call, increment, decrement prefix: sizeof, unary +, unary -, cast, increment, decrement 3. Binary arithmetic ops: + - * / % assignment shorthand assignment

Outline (cont) II. Program Basics 4. Casting implicit promotion hierarchy explicit 5. Side effects 6. Resolving Expressions Precedence Associativity H. Statements 1. Expression 2. Compound

Expressions in C Example: total * TAXRATE Consists of a sequence of operators and operands –operands: total, TAXRATE can be expressions themselves –operator: * operation calculating a result based on the operand(s)

Some Expression Formats primary –expressions that directly map to a value unary –prefix: operator operand –postfix: operand operator binary –operand1 operator operand2 ternary (operator in two parts)

Types for Operands Operators only apply to certain types –e.g., addition applies to numbers Each operand must be of the appropriate type Operators calculate a value Value can then be used as operands to other operators

Primary Expressions identifiers –variable –defined constant literal constants –operands can be values of the appropriate type –operator can have constant (e.g., 5, -34) as operand

Binary Expressions expr1 op expr2 arithmetic operators + - binary addition (e.g., result: 8) - - binary subtraction (e.g., result: 2) * - multiplication (e.g., 5 * 3 result: 15) / - division (e.g., 5 / 3 result: 1) % - remainder (e.g., 5 % 3 result: 2) arithmetic operators apply to number types, result type depends on operand types

Arithmetic Operators Two int operands -> int result Two float operands -> float result / - division operator, is whole number division for ints, floating point division for other operands % - remainder operator, only works for int values Mixed operands (float/int) - result produced is based on a “promotion” hierarchy, result cast to higher type in hierarchy e.g., 5 / 3.0 produces

Promotion Hierarchy Operands of the lower type can be implicitly converted to the higher type (in C) Occurs when an operator expects the higher type (adding together two floats when one is an int)

Assignment Expression varName = expr value of expr determined result of expression is the value of expr as a “side effect” the value calculated is also stored in the named variable (the current value stored in the variable is replaced) example: current value of total is 5 total = 3 replaces the value 5 with the value 3 in the memory location corresponding to total

Assignment Expression (cont) varName = expr expr value must be of the proper type to be stored in the variable (error otherwise) the value may be converted automatically using the promotion hierarchy example: float f; f = 3; /* 3 cast from an integer to a float value */

Shorthand Assignments += -= *= /= %= example: x += 3 is a shorthand for x = x + 3 assuming x is 7 before x += 3 is calculated, the right-hand side x + 3 is calculated, producing 10, this value is then stored in x, and the result of the expression is 10 thus, these operators also have side effects

Unary Expressions Postfix fName(arglist) - function call subprogram is called (invoked) which performs some set of computations and returns a value (more later) Prefix sizeof (expr) - expr can be any primary expression or the name of a type, operator returns num bytes used to represent type (int) + expr - unary plus (applies to numbers, no effect) - expr - unary minus (inverts sign of numbers)

Cast Operator (Unary Prefix Op) (TypeName) expression conversion forces expression value from current type to the provided type example: (float) 5 results in 5.0 especially useful for division example: totalScore, totalGrades (ints) totalScore / totalGrades produces integer (float) totalScore / totalGrades casts totalScore to a floating point number, then division occurs

Prefix Increment, Decrement ++variable - prefix increment --variable - prefix decrement prefix unary operators example: ++x is a shorthand for x = x + 1 similarly --x is a shorthand for x = x - 1 apply to integral values (char, int) have side effect of changing value of variable

Postfix Increment, Decrement variable++ - postfix increment variable-- - postfix decrement postfix unary operators similar to prefix versions BUT different in the value they produce x++ is a shorthand for the statement x = x + 1 but the result of x++ is the value of x BEFORE the value is changed example: assume x is 8, x++ changes x to 9 but returns the value 8 the postfix decrement operator works similarly

Side Effects Certain operations not only produce values, but also perform other actions –assignment statements - change the value of variable on left-hand side of operator –scanf operator - returns a value (number of arguments read), but also changes variables in scanf expression example: scanf(“%d”,&total) changes total

Complex Expressions Expressions can be composed to produce more complex expressions operand of expression can be an expression: total = totalSale + TAXRATE * totalSale three operators, =, +, *, how is this expression resolved?? In C, TAXRATE * totalSale is calculated, then totalSale is added to this value, then this value is stored in total But why??

Resolving Complex Expressions C has precedence, associativity rules it uses to determine the order operators are evaluated in Precedence: some operators are executed before others Associativity: when more than one operator in an expression has the same precedence then associativity rules are used to order

Operator Precedence 18: Identifier, Constant, Parenthesized Expression 17: Function call 16: Postfix increment/decrement, 15: Prefix increment/decrement, sizeof, unary +, unary - 14: (Type) - cast operator 13: * / % 12: + - 2: = += -= *= /= %=

Using Operator Precedence Example: total = totalSale + TAXRATE * totalSale * has highest precedence, so TAXRATE * totalSale is calculated first + has next highest precedence, so the result of TAXRATE * totalSale is added to totalSale = has the lowest precedence, so the value calculated in the previous operations is stored in total

Parenthesized Expressions What if the precedence order is not what you want? example: sale1 + sale2 * TAXRATE in this case the multiplication would happen first, but you might want the addition first answer: parenthesize the expressions you want to happen first result: (sale1 + sale2) * TAXRATE parenthesized expressions have highest precedence

Programming Tip: Parenthesizing Does not hurt to include parentheses for all expressions Thus you can guarantee the order of evaluation Example: total = totalSale + TAXRATE * totalSale becomes total = (totalSale + (TAXRATE * totalSale))

Associativity Rules determining how to evaluate expressions containing more than one operator with the same precedence example: is ((5 - 4) - 3) or (5 - (4 - 3)) its important because the values may differ (e.g., -2 or 4 for the above possibilities) Left associativity: operators are evaluated left to right Right associativity: evaluated right to left

Operator Associativity 18: Identifier, Constant, Parenthesized Expression 17: Function call (LEFT) 16: Postfix increment/decrement (LEFT) 15: Prefix increment/decrement, sizeof, unary +, unary - (RIGHT) 14: (Type) - cast operator (RIGHT) 13: * / % (LEFT) 12: + - (LEFT) 2: = += -= *= /= %= (RIGHT)

Using Operator Associativity Evaluate operators by precedence When evaluating operators with the same precedence, consult associativity rules example: , two - operators, so associativity (left) is used evaluates to ((5 - 4) - 3) or -2 Again, use parentheses to make sure things are evaluated the way you expect

Composing Assignments Example: x = y = 3 (x = (y = 3)) with Right associativity Ok to do, but better to avoid Example: x is 4, what is the result of x = y = x + 3 ? x + 3 evaluated (producing 7), this value stored to y, then the result stored back to x

Multiple Assignments In ANSI C, changing a variable multiple times in the same expression produces an undefined result example: (b-- + b--) is undefined, C may execute both b-- operators together, the left b-- first, or the right b-- first solution: better not to do it

Statements Programs consist of sequences of statements Expressions can be used as part of various types of statements Expressions can also be used as stand-alone statements –generally assignment expressions are issued as separate statements

Expression Statements Format: Expression ; –When the statement is reached in the program the expression is evaluated –Assignment statements cause side effects (change the value of variables) –printf and scanf are actually functions that we call (and produce values), so these are expression statements

Compound Statements A block of code containing zero or more statements Contained between { and } Format: { Local Declarations Statements }

Compound Statements (cont) Example: { int x; /* local declaration */ x = 3; /* statements */ y = x + 4; printf(“%d\n”,y); } Block of statements treated as a unit

Compound Statements (cont) Local declarations exist during the execution of the block/compound statement Declarations are made one at a time Statements are executed from the first to the last Declarations go away once the statements in the block are executed