You are on page 1of 8

Operators

UNIT 5: OPERATORS

Introduction

Operators are special symbols use to perform operations on variables and constant
values. For example, a plus sign ( + ) is used for adding values. Operators can be used along
with some variables and constant. Since, almost all computer programs perform calculations it
is important to know how to make the right formulas with the use of operators available in C++
and their precedence.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Identify the different types of operators.


2. Explain the function of each operator.
3. Explain the precedence of operators or the hierarchy in evaluating operations or
formulas.
4. Construct formulas using the different operators

Course Materials

Now that we know what are variables and constants, we can begin doing some operations
with them with the use of operators.

C++ commonly used operators are the following:

 Assignment operators
 Arithmetic operators
 Comparison operators
 Logical operators

5.1 Assignment Operator ( = )

The equal sign ( = ) is used to assign a value to a receiving variable. It stores the result of
the operation on the right side of the equal sign.

Examples

minFare = 9.00; // assigns or stores 9.00 to variable minFare

32
Operators

grabFareRate = taxiFareRate; // grabFareRate will be the same with the value of

taxiFareRate

dollar2peso = amtDollars * 51.75; // operations can be a combination of variables,

constants and some operators

Note: The format is: receivingVariable = operations;


If you typed, amtDollars * 51.75 = dollar2peso your program will produce an error.

Compound Assignment Operators ( += , - = , * = , /= , %= )

Expression Equivalent to …
a += b; a = a + b;
x -= 10; x = x – 10;
c *= m; c = c * m;
y /= 5; y = y / 5;
d %= 3; d = d % 3;
m *= a + 5; m = m * (a + 5);

5.2 Arithmetic Operators ( +, -, *, /, %)

Arithmetic operators are used to perform common mathematical operations.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo

The last one, modulo operator, represented by a percentage sign (%), gives the remainder
of a division of two values. For example:

x = 15 % 2;

results in variable x containing the value 1, since dividing 15 by 2 is equal to 7, with a remainder
of 1

33
Operators

5.3 Increment and Decrement Operators ( ++, --)

The increment operator (++) and the decrement operator (--) increase or reduce by one
the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:

++x; x+=1; and x = x + 1;

are all equivalent in its functionality; the three of them increase by one the value of x.

It can be used both as a prefix and as a suffix. That means that it can be written either
before the variable name (++x) or after it (x++). This will have an effect if used with other
variables, constants or operators.

Examples:

a = 5; a = 5;
b = a++; b = ++a;

is equivalent to: is equivalent to:

a =5; a = 5;
b = a; a = a + 1;
a = a + 1; b = a;

// b will be equal 5 // b will be equal 6


// a will be equal 6 // a will be equal 6

5.4 Relational or Comparison Operators (==, !=, >, <, >=, <=)

Relational operators are used to compare two values. The return value of a comparison is
either true (1) or false (0).

Operator Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Examples:

(8 == 5) // evaluates to false
(5 > 3) // evaluates to true
(3 != 9) // evaluates to true

34
Operators

(5 >= 5) // evaluates to true


(6 < 6) // evaluates to false

Suppose that a=3, b=2 and c=6, then:

(a == 8) // evaluates to false, since a is not equal to 8


(a*b >= c) // evaluates to true, since (3*2 >= 6) is true
(b+4 > a*c) // evaluates to false, since (2+4 > 3*6) is false
((b=3) == a) // evaluates to true

int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

5.5 Logical Operators ( !, &&, || )

Logical operators are used to determine the logic between variables or values. The return
value of a comparison is either true (1) or false (0). It is used together with relational operations.

Operator Name Description


Reverse the result, if the statement is true
! Logical NOT it will return false

Logical AND Returns true if all statements are true


&& Returns false if at least one of the
statement is false
Returns true if at least one statements is
|| Logical OR true
Returns false if all statements are false

The operator ! in C++ has only one operand, to its right, and inverts it, producing false if
its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean
value of evaluating its operand.

Examples:

!(3 == 3) // evaluates to false because the expression at its


right(3 == 3) is true
!(8 <= 4) // evaluates to true because (8 <= 4) would be false
!true // evaluates to false
!false // evaluates to true

The logical operators && and || are used when evaluating two expressions to obtain a
single relational result. The operator && corresponds to the Boolean logical operation AND,
which yields true if both its operands are true, and false otherwise. The following panel shows
the result of operator && evaluating the expression a&&b:

35
Operators

&& OPERATOR (and)


A b a && b
True true true
True false false
False true false
False false false

The operator || corresponds to the Boolean logical operation OR, which yields true if either
of its operands is true, thus being false only when both operands are false. Here are the
possible results of a||b:

|| OPERATOR (or)
A b a || b
True true true
True false true
False true true
False false false

Examples:

((5 == 5) && (3 > 6)) // evaluates to false ( true && false )

((5 == 5) || (3 > 6)) // evaluates to true ( true || false )

5.6 Operators Precedence

If there are multiple operators in a single expression, from the left to right the operators
with higher precedence is evaluated first.

Example
:
X = 12 – 5 * 2 ; // Answer: 2

5 * 2 will be evaluated first since the multiplication operator ( * ) is of higher precedence


than the subtraction operator ( - ).

If you wish to evaluate 12 – 5 first, then we must enclosed them with parentheses.

X = (12 – 5) * 2 ; // Answer: 14

Note : When an expression has two operators with the same precedence /
level, grouping determines which one is evaluated first: either left-to-right or right-to-left.

Enclosing all sub-statements in parentheses (even those unnecessary because of their


precedence) improves code readability.

36
Operators

C++ Operators Precedence Table (taken from cplusplus.com)

From greatest to smallest priority, C++ operators are evaluated in the following order:

Level Precedence group Operator Description Grouping


Left-to-
1 Scope :: scope qualifier
right
++ -- postfix increment / decrement
() functional forms Left-to-
2 Postfix (unary)
[] subscript right
. -> member access
++ -- prefix increment / decrement
~ ! bitwise NOT / logical NOT
+ - unary prefix
Right-to-
3 Prefix (unary) & * reference / dereference
left
new delete allocation / deallocation
sizeof parameter pack
(type) C-style type-casting
Left-to-
4 Pointer-to-member .* ->* access pointer
right
Left-to-
5 Arithmetic: scaling * / % multiply, divide, modulo
right
Left-to-
6 Arithmetic: addition + - addition, subtraction
right
Left-to-
7 Bitwise shift << >> shift left, shift right
right
Left-to-
8 Relational < > <= >= comparison operators
right
Left-to-
9 Equality == != equality / inequality
right
Left-to-
10 And & bitwise AND
right
Left-to-
11 Exclusive or ^ bitwise XOR
right
Left-to-
12 Inclusive or | bitwise OR
right
Left-to-
13 Conjunction && logical AND
right
Left-to-
14 Disjunction || logical OR
right
= *= /= %= += -
= assignment / compound
Assignment-level >>= <<= &= ^= assignment Right-to-
15
expressions |= left
?: conditional operator
Left-to-
16 Sequencing , comma separator
right

37
Operators

Activities:

Evaluate the following expressions:

1. a = 6;
b = 10;
c = ++a * b--;

what are the values of a, b, and c? a =_______ b=________ c=_________

2. ! ( 5 * (10 / 2 ) >= 17 – 9 / 3 ) True or False

3. x = 3;
y = 7;
z = 8;
z += (x*y); x = ________ y = _______ z= _______

4. pupcet = 80;
hsAve = 78;
public = true;

(pupcet > 75 && hsAve > 80) || public True or False

5. 100 % 32 * 5 + 4 = _______

Write an expression using the appropriate operators for the following:

6. Convert the value in CENTIMETER to Inches.

________________________________________________

7. Get the AMOUNT to pay after deducting 20% to PRICE

________________________________________________

8. Ask whether STATUS is ‘M’ or ‘S’ and WORK is true.

________________________________________________

9. Get 35% of POPULATION.

_________________________________________________

10. Ask whether BRAND is “UNIQLO” and PRICE is less than 1000.

___________________________________________________

38
Operators

Online References

https://www.w3schools.com/cpp/cpp_operators.asp

https://www.tutorialspoint.com/cplusplus/cpp_operators.htm

http://www.cplusplus.com/doc/tutorial/operators/

39

You might also like