PF - Lecture 09-10 Operators and Expressions
PF - Lecture 09-10 Operators and Expressions
area = 2 * PI * radius;
cout << "border is: " << 2*(l+w);
Arithmetic Operators
3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
4
Order of Operations
evaluate
evaluate evaluate third
second first
Order of Operations
9
Mixed Expressions
• Mixed expression:
– Has operands of different data types
– Contains integers and floating-point
• Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
10
Mixed Expressions (continued)
• Evaluation rules:
– If operator has same types of operands
• Evaluated according to the type of the operands
– If operator has both types of operands
• Integer is changed to floating-point
• Operator is evaluated
• Result is floating-point
– Entire expression is evaluated according to precedence rules
11
Algebraic Expressions
20
Type Casting in Program 3-9
C-Style and Pre-standard Type Cast Expressions
sum = sum + 1;
• Using cin with the >> operator to input strings can cause
problems:
– Skips or stops on space, tab, end-of-line, end-of-file
– Skips over leading white space;
– Stops on trailing white space.
• To read any single char mychar (incl. whitespace)
– cin.get(mychar)
• To skip input characters:
– cin.ignore( ); // one character.
– cin.ignore(n); // n characters.
• To work around this problem, you can use a C++ function
named getline.
Working with Characters and string Objects
Flag Meaning
ios::showpoint display the decimal point
ios::fixed fixed decimal notation
ios::scientific scientific notation
ios::right right justification
ios::left left justification
cout Precision and justification
39
Relational Expressions with char
American Standard Code for
Information Interchange
Each
character is
stored in 1
byte
(ASCII binary)
Logical Expressions with String Variables
Logical Expressions with String Variables
Logical (Boolean) Operators
C++ 48
Prog
ram
When do we need parentheses?
Try these in your code
49
C++ Operator Map
Operators
Binary Unary
Arithmetic Logical Bitwise Comparison Arithmetic
+ - add && - and & - and < - less-than - - negate
- - sub || - or | - or > - gt.-than ++ - increment
* - mul ^ - xor <= - less-or-eq -- - decrement
/ - div >= - gt-or-eq Logical
% - mod Copy == - equal ! - negate
= != - not-equal Bitwise
+=, -=, *=, /=, %= ~ - negate
&&=, ||=, &=, |=, ^=
Pointer * ,&
Precedence Chart
Example with Precedence
int a = 0, b = 3, c = 1, d = 4;
a && b || !c || d
52
Precedence
53
Unary Operators
Continued…
Increment and Decrement
Operators in Program 5-1
Prefix vs. Postfix
67
Let’s Evaluate Some examples
68
Thank you