0% found this document useful (0 votes)
7 views

PF - Lecture 09-10 Operators and Expressions

Uploaded by

fahadnae123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PF - Lecture 09-10 Operators and Expressions

Uploaded by

fahadnae123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

CS 1002 Programming Fundamentals

Lecture 09-10 19 & 21 Sept 2022

Operators and Expressions


Mathematical Expressions
• Can create complex expressions using multiple mathematical
operators
• An expression can be a literal, a variable, or a mathematical
combination of constants and variables
• Can be used in assignment, cout, other statements:

area = 2 * PI * radius;
cout << "border is: " << 2*(l+w);
Arithmetic Operators

• Used for performing numeric calculations


• C++ has unary, binary, and ternary operators:
– unary (1 operand) -5
– binary (2 operands) 13 - 7
– ternary (3 operands) exp1 ? exp2 : exp3
Order of Precedence

• All operations inside of () are evaluated first


• *, /, and % are at the same level of precedence and are
evaluated next
• + and – have the same level of precedence and are evaluated
last
• When operators are on the same level
– Performed from left to right (associativity)

3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

4
Order of Operations

In an expression with more than one operator,


evaluate in this order:
- (unary negation), in order, left to right
* / %, in order, left to right
+ -, in order, left to right
In the expression 2 + 2 * 2 – 2

evaluate
evaluate evaluate third
second first
Order of Operations

parentheses ( ) can be used to override the order


of operations:
2 + 2 * 2 – 2 = 4
(2 + 2) * 2 – 2 = 6
2 + 2 * (2 – 2) = 2
(2 + 2) * (2 – 2) = 0
Grouping with Parentheses
A Closer Look at the / Operator

• / (division) operator performs integer division if both operands


are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
• If either operand is floating point, the result is floating point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
• / (division) operator performs integer division if both operands
are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
• If either operand is floating point, the result is floating point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
Expressions

• If all operands are integers


– Expression is called an integral expression
• Yields an integral result
• Example: 2 + 3 * 5
• If all operands are floating-point
– Expression is called a floating-point expression
• Yields a floating-point result
• Example: 12.8 * 17.5 - 34.50

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

• Multiplication requires an operator:


Area=lw is written as Area = l * w;
• There is no exponentiation operator:
Area=s2 is written as Area = pow(s, 2);
• Parentheses may be needed to maintain order of operations:
is written as
y 2  y1
m m = (y2-y1) /(x2-x1);
x 2  x1
Named Constants

• Named constant (constant variable): variable whose content


cannot be changed during program execution
• Used for representing constant values with descriptive names:
const double TAX_RATE = 0.0675;
const int NUM_STATES = 50;
• Often named in uppercase letters
Named Constants in Program 2-28
When You Mix Apples with Oranges: Type
Conversion

• Operations are performed between operands of the same type.


• If not of the same type, C++ will convert one to be the type of
the other
• This can impact the results of calculations.
Hierarchy of Types

Highest: long double


double
float
unsigned long
long
unsigned int
Lowest: int

Ranked by largest number they can hold


Type Coercion

• Type Coercion: automatic conversion of an operand to another


data type
• Promotion: convert to a higher type
• Demotion: convert to a lower type

• Rules of Type Coercion


1) char, short, unsigned short automatically promoted to int
2) When operating on values of different data types, the lower one is
promoted to the type of the higher one.
3) When using the = operator, the type of expression on right will be
converted to type of variable on left
Overflow and Underflow

• Occurs when assigning a value that is too large (overflow) or too


small (underflow) to be held in a variable
• Variable contains value that is ‘wrapped around’ set of possible
values
• Different systems may display a warning/error message, stop
the program, or continue execution using the incorrect value
Type Conversion (Casting)

• Implicit type coercion: when value of one type is automatically changed to


another type

• Cast operator: provides explicit type conversion


static_cast<dataTypeName>(expression)

• Used for manual data type conversion


• Useful for floating point division using ints:
• double m;
m = static_cast<double>(y2-y1)/(x2-x1);

• Useful to see int value of a char variable:


char ch = 'C';
cout << ch << " is "
<< static_cast<int>(ch);
Type Conversion (continued)

20
Type Casting in Program 3-9
C-Style and Pre-standard Type Cast Expressions

• C-Style cast: data type name in ()


cout << ch << " is " << (int)ch;
• Prestandard C++ cast: value in ()
cout << ch << " is " << int(ch);
• Both are still supported in C++, although static_cast is
preferred
Multiple Assignment and Combined Assignment

• The = can be used to assign a value to multiple variables:


x = y = z = 5;
• Value of = is the value that is assigned
• Associates right to left:
x = (y = (z = 5));

value value value


is 5 is 5 is 5
Combined Assignment

• Look at the following statement:

sum = sum + 1;

This adds 1 to the variable sum.


Combined Assignment

• The combined assignment operators provide a


shorthand for these types of statements.
• The statement
sum = sum + 1;
is equivalent to
sum += 1;
Working with Characters and string Objects

• 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

• Mixing cin >> and cin.get() in the same


program can cause input errors that are hard to
detect
• To skip over unneeded characters that are still in
the keyboard buffer, use cin.ignore():
cin.ignore(); // skip next char
cin.ignore(10, '\n'); // skip the next
// 10 char. or until a '\n'
Using getline in Program 3-19
Changing cout behaviour

• Use setf() and unsetf() to set following attributes


– E.g. cout.setf(ios::scientific);

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

• With #include <iomanip> you can use


– setw(n) and setprecision(n)
• E.g.
cin >> n;
cout << setprecision(4)
<< “Sqrt with 4 digits: ” << sqrt(n)
<< endl << “Sqrt right justified: ”
<< setw(10) << sqrt(n) << endl;
Math Functions with <cmath>

abs(x) computes absolute value of x


sqrt(x) computes square root of x, where x >=0
pow(x,y) computes xy
ceil(x) nearest integer larger than x
floor(x) nearest integer smaller than x
exp(x) computes ex
log(x) computes ln x, where x >0
log10(x) computes log10x, where x>0
Trigonometric Functions

sin(x) sine of x, where x is in radians


cos(x) cosine of x, where x is in radians
tan(x) tangent of x, where x is in radians
asin(x) sine-1(x), returns angle in radians [-π/2, π/2]
acos(x) cosine-1(x), returns angle in radians [0,π]
atan(x) tan-1(x), returns angle in radians [-π/2, π/2]
atan2(y,x) tan-1(y/x), returns angle in radians [-π, π]
sinh(x) Hyperbolic sine of x
cosh(x) Hyperbolic cosine of x
tanh(x) Hyperbolic tan of x
Determining the Size of a Data Type

The sizeof operator gives the size of any


data type or variable:
Size of Variables on our system
Use sizeof(<type>)

Build & Run this:


#include <iostream>
• bool: 1 bytes // example if we left out using namespace std;
int main()
• char: 1 bytes {
std::cout << "bool:\t\t" << sizeof(bool) << " bytes" << std::endl;
• short: 2 bytes std::cout << "char:\t\t" << sizeof(char) << " bytes" << std::endl;
• int: 4 bytes std::cout << "short:\t\t" << sizeof(short) << " bytes" << std::endl;
std::cout << "int:\t\t" << sizeof(int) << " bytes" << std::endl;
• long: 8 bytes std::cout << "long:\t\t" << sizeof(long) << " bytes" << std::endl;
std::cout << "float:\t\t" << sizeof(float) << " bytes" << std::endl;
• float: 4 bytes std::cout << "double:\t\t" << sizeof(double) << " bytes" << std::endl;
return 0;
• double: 8 }
bytes
string Member Functions and Operators

• To find the length of a string:

string state = "Texas";


int size = state.length();

• To concatenate (join) multiple strings:


greeting2 = greeting1 + name1;
greeting1 = greeting1 + name2;

Or using the += combined assignment


operator:
greeting1 += name2;
Relational Operators

• Used to compare numbers to determine relative order


• Operators:

> Greater than


< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Relational Expressions

• Boolean expressions – true or false


• Examples:
12 > 5 is true
7 <= 5 is false Can be assigned to a variable:
result = x <= y;
Assigns 0 for false, 1 for true
if x is 10, then
x == 10 is true, Do not confuse = and ==
x != 8 is true, and
x == 8 is false
Some Spaces Matter

Where spaces matter:

• Correct: a>=b a<=b a!=b


• Incorrect: a> =b a< =b a! =b
No space between > and =, < and =, ! and =

Where spaces don’t matter:

• Correct: a>=b a <=b a !=b

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

• Logical (Boolean) operators enable you to combine logical


expressions
• Three logical (Boolean) operators:
– ! - not
– && – and
– || - or
• Logical operators take logical values as operands and yield
logical values as results
• ! is unary; && and || are binary operators
• Putting ! in front of a logical expression reverses its value
Logical (Boolean) Expressions (continued)

• Logical expressions can be unpredictable


• The following expression appears to represent a comparison of
0, num, and 10:
0 <= num <= 10
• It always evaluates true because 0 <= num evaluates to either
0 or 1, and 0 <= 10 is true and 1 <= 10 is true
• A correct way to write this expression is:
0 <= num && num <= 10

C++ 48
Prog
ram
When do we need parentheses?
Try these in your code

(soupTemp > 80) && (soupTemp<95)


is the same as
soupTemp > 80 && soupTemp<95

(soupTemp > 80) && !(soupTemp>=95)


is not the same as
soupTemp > 80 && !soupTemp>=95

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

Logical Operators: Example

int a = 0, b = 3, c = 1, d = 4;
a && b || !c || d

52
Precedence

53
Unary Operators

• Negate: -a gives -9 int a(9);


• Logical-invert: !a gives 0
• * and & are pointer operations (discussed later)
• Increment: ++
• Decrement: --
The Increment and Decrement
Operators

• ++ is the increment operator.

It adds one to a variable.

val++; is the same as val = val + 1;

• ++ can be used before (prefix) or after (postfix) a


variable:
++val; val++;
The Increment and Decrement
Operators

• -- is the decrement operator.

It subtracts one from a variable.

val--; is the same as val = val - 1;

• -- can be also used before (prefix) or after


(postfix) a variable:
--val; val--;
Increment and Decrement
Operators in Program 5-1

Continued…
Increment and Decrement
Operators in Program 5-1
Prefix vs. Postfix

• ++ and -- operators can be used in complex statements and


expressions
• In prefix mode (++val, --val) the operator increments or
decrements, then returns the value of the variable
• In postfix mode (val++, val--) the operator returns the value
of the variable, then increments or decrements
Prefix vs. Postfix - Examples

int num, val = 12;


cout << val++; // displays 12,
// val is now 13;
cout << ++val; // sets val to 14,
// then displays it
num = --val; // sets val to 13,
// stores 13 in num
num = val--; // stores 13 in num,
// sets val to 12
Notes on Increment and Decrement

• Can be used in expressions:


result = num1++ + --num2;
• Must be applied to something that has a location
in memory. Cannot have:
result = (num1 + num2)++;
• Can be used in relational expressions:
if (++num > limit)
pre- and post-operations will cause different
comparisons
More Unary Expressions

• Pre-Increment : int a(9), b;


– b = ++a; b is 10 and a is 10
• Post-Increment:
– b = a++; b is 9 and a is 10
• Pre-Decrement :
– b = --a; b is 8 and a is 8
• Post-Decrement:
– b = a--; b is 9 and a is 8
Ternary Operators

• Ternary operator: conditional operator

X<0 ? Y=10 : z=20;


Nested Ternary Operators
Hand Tracing a Program

• Hand trace a program: act as if you are the computer, executing


a program:
– step through and ‘execute’ each statement, one-by-one
– record the contents of variables after statement execution, using a
hand trace chart (table)
• Useful to locate logic or mathematical errors
Program with Hand Trace Chart
Let’s Evaluate These

• Assume int count = 0 and int limit = 10, try these:


count == 0 && limit < 20
!(count == 12)
(count == 1) && (x < y)
(limit < 20) && (limit/count > 1)
(limit > 10) || (count <= 0) && (count++ >= 0)
! ( ((count < 10) || (x < y) ) && (count >= 0))
(5 && 7) + 16

67
Let’s Evaluate Some examples

• Assume the following


int a = 2, b = 4, c = 6;
• True or false? Don’t worry about short-circuit, doesn’t matter here.
a == 4 || b > 2
6 <= c && a > 3
1 != b && c != 3
a >= -1 || a <= b
!(a>2)
b || (c – a – b) && (a + b) < c
b < 6 <= c

68
Thank you

You might also like