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

Lecture 4-C++ Operators and Expressions

Uploaded by

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

Lecture 4-C++ Operators and Expressions

Uploaded by

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

Lecture 4: C++ Operators and Expressions

In programming, an operator is a symbol that operates on a value or a variable. Operators are


symbols that perform operations on variables and values. For example, + is an operator used for
addition, while - is an operator used for subtraction.

We can also define operators as symbols that help us to perform specific mathematical and
logical computations on operands. In other words, we can say that an operator operates the
operands. For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
Operators in C++ can be classified into 6 types:

i. Arithmetic Operators
ii. Assignment Operators
iii. Relational Operators
iv. Logical Operators
v. Bitwise Operators
vi. Other Operators
Operators can further be categorized as; Unary, Binary and Ternary operators.

a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example:
Increment (++) and Decrement (--) Operators
int val = 5;
cout<<++val; // 6

1|Page
@myco…TCBE 2202 Computing for Civil Engineering
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example: Addition
(+), Subtraction (-), multiplication (*), Division (/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9

C) Conditional (ternary) operator:


The conditional (ternary) operator takes three operands: a condition followed by a question mark
(?). In C++, the ternary operator can be used to replace if...else in certain scenarios. The ternary
operator takes 3 operands (condition, expression1 and expression2). Hence, the name ternary
operator. This will be discussed later in detail under Flow control statements.

1. C++ Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
++ -- Increment (++) and Decrement (--) the value of the object respectively

Example 1: Arithmetic Operators


#include <iostream>
int main()
{
int x = 123;
int y = 456;
int z = x + y; // addition
z = x - y; // subtraction
z = x * y; // multiplication
z = x / y; // division
std::cout << "The value of z is: " << z << '\n';
}
Output:

2|Page
@myco…TCBE 2202 Computing for Civil Engineering
The integer division, in our example, results in a value of 0. It is because the result of the integer
division where both operands are integers is truncated towards zeros. In the expression x / y, x and
y are operands and / is the operator.

Example 2: Arithmetic Operators

#include <iostream>
using namespace std;

int main() {
int a, b;
a = 7;
b = 2;

// printing the sum of a and b


cout << "a + b = " << (a + b) << endl;

// printing the difference of a and b


cout << "a - b = " << (a - b) << endl;

// printing the product of a and b


cout << "a * b = " << (a * b) << endl;

// printing the division of a by b


cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b


cout << "a % b = " << (a % b) << endl;

return 0;
}
Run Code

Output

a + b = 9
a - b = 5
a * b = 14
a / b = 3
a % b = 1

Here, the operators + , - and * compute addition, subtraction, and multiplication respectively as
we might have expected.

3|Page
@myco…TCBE 2202 Computing for Civil Engineering
/ Division Operator:
Note the operation (a / b) in our program. The / operator is the division operator. As we can
see from the above example, if an integer is divided by another integer, we will get the quotient.
(It is because the result of the integer division where both operands are integers is truncated to
whole number). However, if either divisor or dividend is a floating-point number, we will get the
result in decimals.

In C++,

7/2 is 3

7.0 / 2 is 3.5

7 / 2.0 is 3.5

7.0 / 2.0 is 3.5

Thus: For division operator, If we want a floating-point result, we need to use the type double and
make sure at least one of the division operands is also of type double: For example;

#include <iostream>
int main()
{
int x = 123;
double y = 456;
double z = x / y;
std::cout << "The value of z is: " << z << '\n';
}
Output:

Similarly, we can have:


#include <iostream>
int main()
{
double z = 123 / 456.0;
std::cout << "The value of z is: " << z << '\n';
}
and the result would be the same.

4|Page
@myco…TCBE 2202 Computing for Civil Engineering
% Modulo Operator:
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the
remainder is 1.

Note: The % operator can only be used with integers.

Note: Arithmetic operators are of two types: (i) binary operators (e.g. Addition (+), Subtraction
(-), multiplication (*), Division (/), modulo (%) operators) and (ii) unary operators (e.g.
Increment (++) and Decrement (--) Operators).
Increment and Decrement Operators:
Increment/decrement operators increment/decrement the value of the object. C++ also provides
increment and decrement operators: ++ and -- respectively.
++ increases the value of the operand by 1
-- decreases it by 1
The operators are:
• ++x // pre-increment operator
• x++ // post-increment operator
• --x // pre-decrement operator
• x-- // post-decrement operator
For example,

int num = 5;

// increment operator
++num; // 6

Here, the code ++num; increases the value of num by 1.

A simple example:
#include <iostream>
int main()
{
int x = 123;
x++; // add 1 to the value of x
++x; // add 1 to the value of x
--x; // decrement the value of x by 1
x--; // decrement the value of x by 1
std::cout << "The value of x is: " << x;
}

5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Both pre-increment and post-increment operators add 1 to the value of our object, and both pre-
decrement and post-decrement operators subtract one from the value of our object. The difference
between the two, apart from the implementation mechanism (very broadly speaking), is that with
the pre-increment operator, a value of 1 is added first. Then the object is evaluated/accessed in
expression. With the post-increment, the object is evaluated/accessed first, and after that, the value
of 1 is added. To the next statement that follows, it does not make a difference. The value of the
object is the same, no matter what version of the operator was used. The only difference is the
timing in the expression where it is used.

Example 3: Increment and Decrement Operators


// Working of increment and decrement operators

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 100, result_a, result_b;

// incrementing a by 1 and storing the result in result_a


result_a = ++a;
cout << "result_a = " << result_a << endl;

// decrementing b by 1 and storing the result in result_b


result_b = --b;
cout << "result_b = " << result_b << endl;

return 0;
}
Run Code

Output

result_a = 11
result_b = 99

In the above program, we have used the ++ and -- operators as prefixes (++a and --b). However,
we can also use these operators as postfix (a++ and b--).

6|Page
@myco…TCBE 2202 Computing for Civil Engineering
2. C++ Assignment Operators
The assignment operator = assigns a value to a variable / object: Therefore, in C++, assignment
operators are used to assign values to variables. For example,

// assign 5 to a
a = 5;

Here, we have assigned a value of 5 to the variable a.

The left side operand of the assignment operator is a variable and the right side operand of the
assignment operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
Operator Example Equivalent to
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

i) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right
to the variable on the left.

Example 1:
int main()
{
char mychar = 'c'; // define a char variable mychar
mychar = 'd'; // assign a new value to mychar
int x = 123; // define an integer variable x
x = 456; // assign a new value to x
int y = 789; // define a new integer variable y
y = x; // assing a value of x to it
}

7|Page
@myco…TCBE 2202 Computing for Civil Engineering
ii) Compound Assignment Operators
Compound assignment operators allow us to perform an arithmetic operation and assign a result
with one operator:
+= // compound addition
-= // compound subtraction
*= // compound multiplication
/= // compound division
%= // compound modulo

Example 2:
#include <iostream>
int main()
{
int x = 123;
x += 10; // the same as x = x + 10
x -= 10; // the same as x = x - 10
x *= 2; // the same as x = x * 2
x /= 3; // the same as x = x / 3
std::cout << "The value of x is: " << x;
}

a) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

b) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on
the right from the current value of the variable on left and then assigns the result to the variable
on the left.

Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
8|Page
@myco…TCBE 2202 Computing for Civil Engineering
c) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.

Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
d) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the variable
on the left.

Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.

General Example: Assignment Operators

#include <iostream>
using namespace std;

int main() {
int a, b;

// 2 is assigned to a
a = 2;

// 7 is assigned to b
b = 7;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;

// assigning the sum of a and b to a


a += b; // a = a +b
cout << "a = " << a << endl;

return 0;
}
Run Code

9|Page
@myco…TCBE 2202 Computing for Civil Engineering
Output

a = 2
b = 7

After a += b;
a = 9

3. C++ Relational Operators


These are used for the comparison of the values of two operands. For example, checking if one
operand is equal to the other operand or not, whether an operand is greater than the other operand
or not, etc.
Thus, a relational operator is used to check the relationship between two operands. For example,

// checks if a is greater than b


a > b;

Here, > is a relational operator. It checks if a is greater than b or not. If the relation is true, it
returns 1 whereas if the relation is false, it returns 0. Some of the relational operators are;
Operator Meaning Example
== Is Equal To 3 == 5 gives us false
!= Not Equal To 3 != 5 gives us true
> Greater Than 3 > 5 gives us false
< Less Than 3 < 5 gives us true
>= Greater Than or Equal To 3 >= 5 give us false
<= Less Than or Equal To 3 <= 5 gives us true
Example 1
#include <iostream>
using namespace std;

int main() {
int a = 3;
int b = 5;
cout<<(a < b)<< endl; // operator to check if a is smaller than b
return 0;
}

Output:

Note: Relational operators are used in decision-making and loops.

10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 2: Relational Operators

#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;

result = (a == b); // false


cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;
}
Run Code

Output

3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1

11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
4. C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression
is true, it returns 1 whereas if the expression is false, it returns 0.

Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. Therefore, the result of the operation of a
logical operator is a Boolean value either true or false.

Operator Example Meaning

expression1 && Logical AND.


&&
expression2 True only if all the operands are true.

Logical OR.
expression1 ||
|| True if at least one of the operands is
expression2
true.

Logical NOT.
! !expression
True only if the operand is false.

In C++, logical operators are commonly used in decision making. To further understand the logical
operators, let's see the following examples,

Suppose,
a = 5
b = 8

Then,

(a > 3) && (b > 5) evaluates to true


(a > 3) && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true


(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false

!(a < 3) evaluates to true


!(a > 3) evaluates to false

12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 1: Logical Operators
#include <iostream>
using namespace std;

int main() {
bool result;

result = (3 != 5) && (3 < 5); // true


cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false


cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false


cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true


cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true


cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false


cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true


cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false


cout << "!(5 == 5) is " << result << endl;

return 0;
}
Run Code

13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Output

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Explanation of logical operator program


• (3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
• (3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
• (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
• (3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
• (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
• (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
• !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
• !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).

5. C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual bits. They can only be
used alongside char and int data types.

Operator Description

& Binary AND

| Binary OR

^ Binary XOR

~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing. For example, the bitwise AND operator represented as ‘&’ in
C takes two numbers as operands and does AND on every bit of two numbers. The result of
AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010

6. Other C++ Operators


Here's a list of some other common operators available in C++.
Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

returns value based on the string result = (5 > 0) ? "even" :


?:
condition "odd"; // "even"

represents memory address


& &num; // address of num
of the operand

accesses members of struct


. s1.marks = 92;
variables or class objects

used with pointers to access


-> ptr->marks = 92;
the class or struct variables

<< prints the output value cout << 5;

>> gets the input value cin >> num;

15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Some of them are discussed here:
a. sizeof operator
• sizeof is much used in the C programming language.
• It is a compile-time unary operator which can be used to compute the size of its operand.
• The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
• Basically, the sizeof the operator is used to compute the size of the variable.

b. Comma Operator
• The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
• The comma operator has the lowest precedence of any C operator.
• Comma acts as both operator and separator.

c. Conditional Operator
• The conditional operator is of the form Expression1? Expression2: Expression3
• Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then
we will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
• We may replace the use of if..else statements with conditional operators.

d. dot (.) and arrow (->) Operators


• Member operators are used to reference individual members of classes, structures, and
unions.
• The dot operator is applied to the actual object.
• The arrow operator is used with a pointer to an object.

e. Cast Operator
• Casting operators convert one data type to another. For example, int(2.2000) would return 2.
• A cast is a special operator that forces one data type to be converted into another.
• The most general cast supported by most of the C compilers is as follows − [ (type)
expression ].

f. &,* Operator
• Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
• Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var.

16 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Operators Precedence in C++:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Show Examples
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

17 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example

Try the following example to understand operators precedence concept available in C++. Copy
and paste the following C++ program in test.cpp file and compile and run this program.

Check the simple difference with and without parenthesis. This will produce different results
because (), /, * and + have different precedence. Higher precedence operators will be evaluated
first:
#include <iostream>
using namespace std;
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
cout << "Value of (a + b) * c / d is :" << e << endl ;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl ;
e = (a + b) * (c / d); // (30) * (15/5)
cout << "Value of (a + b) * (c / d) is :" << e << endl ;

e = a + (b * c) / d; // 20 + (150/5)
cout << "Value of a + (b * c) / d is :" << e << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is :90
Value of a + (b * c) / d is :50
Note: Read and write notes about C++ Operator Overloading and C++ Expressions

18 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
C++ Expression
C++ expression consists of operators, constants, and variables which are arranged according to the
rules of the language. It can also contain function calls which return values. An expression can
consist of one or more operands, zero or more operators to compute a value. Every expression
produces some value which is assigned to the variable with the help of an assignment operator.

Examples of C++ expression:


(a+b) - c
(x/y) -z
4a2 - 5b +c
(a+b) * (x+y)
Every expression (even assignment) has a type and a result. An expression can be of following
types:
• Constant expressions
• Integral expressions
• Float expressions
• Pointer expressions
• Relational expressions
• Logical expressions
• Bitwise expressions
• Special assignment expressions

If the expression is a combination of the above expressions, such expressions are known as
compound expressions.

• Operator precedence provides an unambiguous interpretation for every expression.


• An expression (e.g. x=0) becomes a statement when followed by a semicolon (i.e. x=0;)
• Several expressions can be separated using a comma ‘,’; expressions are then evaluated left
to right; for example: x=0,y=1.0
• The type and value of a comma-separated expression is the type and value of the result of
the right-most expression.

19 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering

You might also like