Expressions in C++
Expressions in C++
Expressions in C++
Arithmetic 2
Arithmetic 3
Arithmetic Operators
The built-in arithmetic operations are
• Addition +
• Subtraction
• Multiplication *
• Division /
• Modulus % (remainder)
Arithmetic 4
Arithmetic expression
• An arithmetic operator can be used with any numeric type
• An operand is a number or a variable used by an operator
• Results of the operator depend upon the types of
operands
Division /
Integer Division
Arithmetic 7
Modulus %
% operator gives the remainder from integer
division
int divisor, dividend, remainder;
divisor=3
dividend=5;
remainder=dividend % divisor;
Z = P * R % Q + W / X - Y ;
6 1 2 4 3 5
Arithmetic 10
Program
// Prints the sum, difference, etc. of given integers.
#include <iostream>
void main(){
int m = 6, n = 7;
cout << "The integers are " << m << " and " << n << endl;
cout << "Their sum is " << (m+n) << endl;
cout << "Their difference is " << (m-n) << endl;
cout << "Their product is " << (m*n) << endl;
cout << "Their quotient is " << (m/n) << endl;
cout << "Their remainder is " << (m%n) << endl << endl << endl;
}
Arithmetic 11
Assignment Expression
We will usually see an assignment operation in this format:
<variable> = <expression>
For example,
c = 0;
c = c + 3;
average = sum / count;
Arithmetic 12
Compound Assignment
c = c + 3; same as c +=3;
The += operation adds the value of the expression of the right to the
value of the variable on the left and stores the result in the variable on the
left.
In general, <var> = <var> op <exp>; can be written as:
<var> op = <exp>;
Examples:
c = 4; //same as c = c 4;
c *= 5; //same as c = c *5;
c /= 6; //same as c = c /6;
Can we reverse the order of the double operator? Say, c = 4;
No. This simply is the same as the assignment c = 4;
Arithmetic 13
int c;
c = 5;
cout << c << endl; // outputs 5
cout << c++ << endl; // outputs 5 (then increments)
cout << c << endl << endl; // outputs 6
c = 5;
cout << c << endl; // outputs 5
cout << ++c << endl; // outputs 6 (after incrementing)
cout << c << endl; // outputs 6
Grade Point Average Arithmetic 15
}
Arithmetic 18
Relational operator
• A Boolean expression is an expression that is either
true or false.
• Boolean expressions are evaluated using relational
operations such as:-
==
!=
<
>
<=
>=
Arithmetic 20
Logical operator
Combine two relational expressions
• &&
• ||
•!
Arithmetic 21
Arithmetic 22
Boolean Expressions
Boolean expressions are evaluated using values from the truth table
!(false)||(true)
!(true)
false
Arithmetic 23
Review