Learn C++ Programming Language
Operators in C++ Programming
Definition of C++ Operators
There are many operators for manipulating numeric values and performing arithmetic operations. C++ provides many operators for manipulating data. Generally, there are three types of operators: unary, binary, and ternary.
These terms reflect the number of operands an operator requires. Unary operators only require a single operand. Binary operators work with two operands. Ternary operators, as you may have guessed, require three operands.
The arithmetic operators can be used for appropriate combinations of these types:
- x+y // plus
- + x // unar y plus
- x − y // minus
- − x // unar y minus
- X * y //multiply
- x / y // divide
- x % y // remainder (modulus) for integers
The comparison operators in C++ are:
- x == y // equal
- x != y // not equal
- x < y // less than
- x > y // greater than
- x <= y //less than or equal
- x >= y // greater than or equal
Furthermore, logical operators are provided:
- x & y // bitwise and
- x | y // bitwise or
- x ˆ y // bitwise exclusive or
- ˜x // bitwise complement
- x && y // logical and
- x || y // logical or
C++ example with arithmetic operators
This examples program calculates hourly wages, including overtime.
#include <iostream.h>
using namespace std;
int main()
{
double basePayRate = 18.25, // Base pay rate
overtimePayRate = 27.38, // Overtime pay rate
regularHours = 40.0, // Regular hours worked
overtimeHours = 10, Overtime hours worked//
regularWages, // Computed regular wages
overtimeWages, // Computed overtime wages
totalWages; // Computed total wages
// Calculate regular wages
regularWages = basePayRate * regularHours;
// Calculate overtime wages
overtimeWages = overtimePayRate * overtimeHours;
// Calculate total wages
totalWages = regularWages + overtimeWages;
// Display total wages
cout << "Wages for this week are $" << totalWages << endl;
return 0;
}
Output:
Wages for this week are $1003.8
The regular hours for the work week are 40, and any hours worked over 40 are considered overtime. The employee earns $18.25 per hour for regular hours and $27.38 per hour for overtime hours. The employee has worked 50 hours this week.
Notice that the output displays the wages as $1003.8, with just one digit after the decimal point.
Ads Right