1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
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.
True or false A variable of type char can hold the value 301. ( F )
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
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.
Operations and Expressions Chapter 3. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further work with Object-Centered Design Detailed look at.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Data types and variables
Operations and Expressions. Computer Programming 2 Objectives Detailed look at numeric operations Work with bool expressions Consider the processing of.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Admin Office hours 2:45-3:15 today due to department meeting if you change addresses during the semester, please unsubscribe the old one from the.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Expressions, Data Conversion, and Input
Objectives You should be able to describe: Data Types
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 3: Data Types and Operators JavaScript - Introductory.
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.
Operations Making Things Happen. Our Scuba Program #include // cin, cout, > using namespace std; int main() { const double FEET_PER_ATM = 33.0, LBS_PER_SQ_IN_PER_ATM.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
Operations and Expressions Chapter 3. C++ An Introduction to Computing, 3rd ed. 2 Objectives Further work with Object-Centered Design Detailed look at.
Chapter 2: Using Data.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
PROCESSING Numeric Types. Objectives Be able to … Explain the difference between a literal, a variable and a constant Declare numeric variables and constants.
C++ Programming: Basic Elements of C++.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
CPS120: Introduction to Computer Science Operations Lecture 9.
1 Operations Making Things Happen (Chap. 3) Expressions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
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.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
1 Operations Chapter 4 & Section Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 CS161 Introduction to Computer Science Topic #6.
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.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
Programming Fundamentals. Summary of Previous Lectures Phases of C++ Environment Data Types cin and cout.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
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.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
1 Chapter 3 – Operators and Expressions Outline 3.1Introduction 3.2Arithmetic operators 3.3Relational operators 3.4Logical operators 3.5Assignment operators.
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.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Operations Making Things Happen.
Chapter 7: Expressions and Assignment Statements
Computing and Statistical Data Analysis Lecture 2
Computing Fundamentals
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Operators and Expressions
Lecture 3 Expressions Richard Gesick.
Chapter-3 Operators.
Conversion Check your class notes and given examples at class.
Primitive Types and Expressions
C++ Programming Language Lecture 4 C++ Basics – Part II
OPERATORS AND EXPRESSIONS IN C++
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
OPERATORS in C Programming
Presentation transcript:

1 Operations 4 & Section 5.2 Chapter 4 & Section 5.2

Expressions As we've seen, in a C++ program, any finite sequence of objects and operations that combine to produce a value is called an expression. A temperature conversion example: fahrenheit = 1.8 * celsius + 32; We now consider C++ operations. 2 Why not fahrenheit = 9/5 * celsius + 32; ?

Numeric Expressions C++ provides four familiar arithmetic operators: + for performing addition - for performing subtraction * for performing multiplication / for performing division Each can be applied to either real ( double ) or integer ( int ) [or character ( char )] operands. 3 C++ provides more than 50 operations (See Appendix C) mult. symbols: <<. ++, words ((sizeof)

Division However, / behaves differently for int than for double operands: / 5  9 / 5.0  Type of Operands Kind of Division Performed int integer real 9.0 / 5.0  9 / 5  double Integer division calculates the quotient, but it also calculates the remainder. To find it we can use the modulus operator % ; for example, 9 % 5 =. 4 “guzinta” b = aq + r

2 % 3 = 456 / 100 = 456 % 100 = 1 / 2 = 56 / 10 = 56 % 10 = 1 % 2 = 2 / 3 = More examples: Keep in mind for Project 3 What about mixed-mode (i.e., mixed-type) expressions? Automatic Type Conversion (p. 73): Promotion: "Narrower" types (fewer storage bits) "widened" e.g., int  double ; 9.0/5  9.0/5.0 Explicit Type Conversion (p. 73-4): Type Casting Use type name to convert an expression: double(intVal) or (double)intVal Functional Notation Cast Notation b = aq + r Assign 3 – chang maker double(a) / double(b)

Numeric Functions The library contains a variety of mathematical functions, including: sin(x) asin(x) cos(x)acos(x) tan(x) atan(x) sqrt(x)abs(x) exp(x)pow(x, y) log(x)floor(x) log10(x)ceil(x) 6 Hyperbolic functions: cosh(x), sinh(x), tanh(x) See Appendix D for other math functions and other libraries. sqrt(<0) nan -1.#IND pow(x, 1/3) efficiency –Asgn 2: quadratic

Using functions int main() { cout << "\nEnter base and exponent: "; double base, exponent; cin >> base >> exponent; double result = pow(base, exponent); cout << base << " raised to the power " << exponent << " is " << result << endl; } 7 #include using namespace std; C++ libraries whose names start with 'c' are C libraries. Their C-names do not have the 'c' but have.h appended; e.g., Essentially same as '\n'

Precedence ( or priority) Issue: Is the value of the expression * 4 (2 + 3) * 4  24 or 2 + (3 * 4)  14 ? Operator precedence governs evaluation order. * has higher precedence than +, so it is applied first, making the answer See Slide #32 int a = 8, b = 4, c = 2 pow(a, 2) + b * c -> 72 a/b+c -> 4 a/(b+c_ -> 1

Associativity Does the expression evaluate (8 - 4) - 2  2 or 8 - (4 - 2)  6 ? Precedence doesn’t help us. Associativity does. Since - is left-associative, the left - is evaluated first. 9 Most of the C++ operators that we use associate left. See Appendix C for a complete list. int a = 8, b = 4, c = 2 a – b + c a / b*c See App. D

Assignment The rightmost = is applied first, assigning z zero, then y is assigned the value of z (0), 10 w = x = y = z = 0 ; then x is assigned the value of y (0), and finally w is assigned the value of x (0). Assignment is one operator that is right- associative, which allows expressions like: int w, x, y, z; w = x = y = z = 0; Mixed-mode assignments convert the value to type of variable and assign it. Assignment operator returns the value being assigned. ( ) double pi = ; int w = pi; 3 ; pi = w 3.0 y = 2*(x = a + b) + c

Assignment Shortcuts Certain assignments are very common: var = var + x; // add x to var var = var - y; // sub y from var C++ provides shortcuts for them: // add x to var // sub y from var var += x; var -= y; 11 Watch out! x += 2; x =+2; Don’t use?

In General Most arithmetic expressions of the form: var = var  value; can be written in the "shortcut" form: var  = value; Examples: double x, y; cin >> x >> y; // double x’s value // decrease y by half x *= 2.0; y /= 2.0; 12

Increment and Decrement Other common assignments include: var = var + 1; // add 1 to var var = var - 1; // sub 1 from var so C++ provides shortcuts for them, too: // add 1 to var // sub 1 from var var++; ++var; var--; --var; 13 Integer variables only!

Prefix vs. Postfix As long as the increment (or decrement) operator is used as a separate statement: int y = 0, x = 0;... ++x; // x becomes y++; // y becomes it makes no difference which version is used. 14  1 1

However, ++ and -- can be used within other expressions; then it does make a difference whether it is prefix or postfix. The prefix form of increment produces the final (incremented) value as its result: int x, y = 0; x = 2 * (++y); cout << x << " " << y; // The prefix decrement -- behaves similarly is displayed  

The postfix form of increment produces the original (unincremented) value as its result: int x, y = 0; x = 2 * (y++); cout << x << " " << y; // The prefix decrement -- behaves similarly. 0 1 is displayed 16 

I/O 17 In most programming languages, input and output are performed by functions with names like read() and print(). In C++, however, (but not C) they are performed by operators >> and << : input_stream >> variable output_stream << expression. printf, scanf

18 We know that: cin >> variable reads a value from the keyboard and assigns it to variable cout << expression outputs the value of expression to the screen. But these are side effects. Because >> and << are operators, these i/o expessions must also produce a value. cin >> variable returns ____ as its value; cout << expression returns _____ as its value. cin cout Use at end of course

19 Arithmetic operators can be chained together in expressions like a + b + c and a - b - c. Input and output operators can also be chained; for example: cout << "Width =" << width << " ft.\n"; and cin >> length >> width; These work because of the values returned by >> and << and both are ___-associative. Why??? left skim

20 Example: cout << "Width =" << width << " ft.\n"; (cout << "Width =") << width << " ft.\n"; ____ << width << " ft.\n"; (cout << width) << " ft.\n"; ____ << " ft.\n"; ____ cout cout; Width = 8.5 ft. skim

Relational Operations x == y x != y x = y x > y x <= y 21 C++ provides six operators for comparisons. Each has two operands and produces a bool value (true or false): Warning: 1 < x < 2 boolean expressions Chap. 5: prep. for control list on board §5.2

22 C, the parent language of C++, has no bool type. Instead, it uses 0 to represent false and nonzero values to represent true. For upward compatibility, C++ also does this: 0 is interpreted as false nonzero is interpreted as true For input and output, 0 is used for false, 1 for true (see program on Slide #29) unless boolalpha is inserted in an I/O statement (see modification of program on Slide #29). It remains in effect for rest of program (unless noboolalpha is used in an I/O statement). dec, oct, hex

Also, it can be dangerous to compare reals with == and != when one or both of the reals may have roundoff error. See the program on Slide #25. One of the easiest mistakes to make in C++ is using in place of == (equality). See the program on Slide # = (assignment)

#include using namespace std; int main() { int x; cout << "Enter an integer: "; cin >> x; if (x = 99) cout << "Yes\n"; else cout << "No\n";} 24 Executions: Enter an integer: 99 Yes Enter an integer: -99 Yes Enter an integer: 0 Yes With change: if (x 99) if (x == 99) Enter an integer: 99 Yes Enter an integer: -99 No Enter an integer: 0 No

//-- Effect of roundoff error #include using namespace std; int main() { for (float x = 0; x != 50.0; x = x + 0.1) { float y = x * sqrt(1 + sin(x)); cout << x << " " << y << endl;; } 25 Execution: With change: for (float x = 0; x < 50.0; x = x + 0.1) Execution: or abs(x - 50) >= 1E-10

Preconditions Sometimes values must satisfy certain requirements for a program to process them (e.g., they must be positive). if statement later Such requirements are called preconditions or assertions. They are boolean expressions that must be true in order for the program to work correctly. A convenient way to check preconditions is to use C++’s assert() mechanism. e.g., Project Proj. 2 b^2 > 4ac Proj. 3: payment > purchase

Assertions #include using namespace std; int main() { cout > month; assert(month >= 1); assert(month <= 12); 27 #include //... } assert() will halt the program if month 12 and display a message. assert1

NOTE Logical Operators More complex boolean expressions can be built using the logical operators: b1 && b1 // true iff b1, b2 are both true b1 || b2 // true iff b1 or b2 is true !b // true iff b is false Example: cin >> month; 28 assert(1 <= month && month <= 12); NOT: assert(1 <= month <= 12); assert1

#include using namespace std; int main() { bool input1, input2, output; cout << "Enter inputs: "; cin >> input1 >> input2; output = (input1 || input2) && !(input1 && input2); cout << "Output for inputs " << input1 << " and " << input2 << " is " << output << '\n'; } 29 Executions: Enter inputs: 0 1 Output for inputs 0 and 1 is 1 Enter inputs: 1 1 Output for inputs 1 and 1 is 0 With change: cout << "Output for inputs " << boolalpha << input1 << " and " << input2 << " is " << output << '\n'; Enter inputs: 0 1 Output for inputs false and true is true With change: cin >> boolalpha >> input1 >> input2; Enter inputs: false true Output for inputs false and true is true Binary Half- Adder: (§5.3) Full Adder: (Programming Problems) XOR circuit

Character Functions The library contains an assortment of boolean character-processing functions: isalpha(ch) isalnum(ch) isdigit(ch) iscntrl(ch) islower(ch) isupper(ch) isspace(ch) ispunct(ch) isprint(ch) isgraph(ch) and two case-conversion functions: toupper(ch) tolower(ch) 30 See App. D

Write an assertion that will halt the program if a char object named ch is not an uppercase letter: 31 Write an assertion that will halt the program if ch is not one of 'A' through 'G': assert('A' <= ch && ch <= 'G'); assert('A' <= ch && ch <= 'Z'); or or assert(isupper(ch)); Examples: use later - menu

Operator Precedence ( ) HIGHER + (positive), - (negative), ! (NOT) *, /, % + (addition), - (subtraction), >= > ==, != && || = LOWER See Appendix C for a complete list. 54 operators 18 precedence levels 32 When in doubt, use parentheses!

33 OperatorAssociativityOverloadableArityDescription :: rightnounaryglobal scope :: leftnobinaryclass scope.leftnobinarydirect member selection - leftyesbinaryindirect member selection [] leftyesbinarysubscript (array index) () leftyesn/afunction call () leftyesn/atype construction sizeof rightn/aunarysize (in bytes) of an object or type ++ rightyesunaryincrement -- rightyesunarydecrement ~ rightyesunarybitwise NOT ! rightyesunarylogical NOT + rightyesunaryplus (sign) - rightyesunaryminus (sign) * rightyesunarypointer dereferencing & rightyesunaryget address of an object new rightyesunarymemory allocation delete rightyesunarymemory deallocation () rightyesbinarytype conversion (cast). leftnobinarydirect member pointer selection -> leftyesbinaryindirect member pointer selection * leftyesbinarymultiplication / leftyesbinarydivision % leftyesbinarymodulus (remainder) + leftyesbinaryaddition - leftyesbinarysubtraction << leftyesbinarybit-shift left >> leftyesbinarybit-shift right < leftyesbinaryless-than <= leftyesbinaryless-than-or-equal > leftyesbinarygreater-than >= leftyesbinarygreater-than-or-equal == leftyesbinaryequality != leftyesbinaryinequality & leftyesbinarybitwise AND ^ leftyesbinarybitwise XOR | leftyesbinarybitwise OR && leftyesbinarylogical AND || leftyesbinarylogical OR ? : leftnoternaryconditional expression = rightyesbinaryassignment += rightyesbinaryaddition-assignment shortcut -= rightyesbinarysubtraction-assignment shortcut *= rightyesbinarymultiplication-assignment shortcut /= rightyesbinarydivision-assignment shortcut %= rightyesbinarymodulus-assignment shortcut &= rightyesbinarybitwise-AND-assignment shortcut |= rightyesbinarybitwise-OR-assignment shortcut ^= rightyesbinarybitwise-XOR-assignment shortcut <<= rightyesbinarybitshift-left-assignment shortcut >>= rightyesbinarybitshift-right-assignment shortcut throw rightyesunarythrow an exception, leftyesbinaryexpression separation