Chapter 2 Part 3
Chapter 2 Part 3
Chapter 2 Part 3
Arithmetic's Operators
The five arithmetical operations supported
by the C++ language are:
+ addition
- subtraction
* multiplication
/ division
% modulus
Types of Operators
Assignment (=)
The assignment operator assigns a value to a
variable.
a = 5;
a = b;
Types of Operators
#include <iostream.h> 5
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
return 0;
}
Types of Operators
1. c++;
2. c+=1;
3. c=c+1;
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4 // A contains 3
Types of Operators
!= Not equal to
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Types of Operators
&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
Types of Operators
a b a || b
true true true
true false true
false true true
false false false
Types of Operators
For example:
Conditional operators
ternary operator (working on three values)
Format:
conditional Expression ? expression1 :expression2;
if the conditional Expression is true, expression 1
executes, otherwise if the conditional Expression is
false, expression 2 executes
Types of Operators
Example
(a>b) ? (c=25) : (c=45);
Program:
#include<iostream.h>
void main()
{
int a,b,c;
a=4;
b=5;
(a > b) ? (c=25) : (c=35);
cout<<a+c;
}
Typecasting
Example:
cout<< char ( 65 ) ;
The (char) is a typecast, telling the computer to
interpret the 65 as a character, not as a
number. It is going to give the character output
of the equivalent of the number 65 (It should be
the letter A for ASCII).
Operators’ Precedence
a = 5 + (7 % 2) // with a result of 6, or
a = (5 + 7) % 2 // with a result of 0
Operators’ Precedence
Examples:
a. 25 + 18 * 2;
b. 3.00*40+1.5*6+10;
c. 2*payrate+bonus;
d. (4==4)
e. (grossPay > taxableAmount)
Apply expression and operators in
program
#include <iostream.h>
int main()
{
float payrate;
float hours;
float totalPay;
totalPay=payrate*hours;
cout<<”\nTotal pay is RM “<<totalPay<<endl;
}