Understanding C++ Operators - Arithmetic, Comparison, and Logical
C++ provides various operators that allow you to perform operations on data. Operators are essential in programming and are classified into different categories, including arithmetic, comparison, and logical operators. In this guide, we'll explore these types of operators in C++.
Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric values. Here are some common arithmetic operators:
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus (remainder of division)
Example:
int a = 10;
int b = 5;
int sum = a + b; // sum is now 15
int product = a * b; // product is now 50
Comparison Operators
Comparison operators are used to compare values. They return either true
or false
. Common comparison operators include:
==
: Equal to!=
: Not equal to<
: Less than<=
: Less than or equal to>
: Greater than>=
: Greater than or equal to
Example:
int x = 10;
int y = 20;
bool isEqual = (x == y); // isEqual is false
bool isGreater = (x > y); // isGreater is false
Logical Operators
Logical operators are used to combine and manipulate boolean values (true
or false
). Common logical operators include:
&&
: Logical AND||
: Logical OR!
: Logical NOT
Example:
bool isSunny = true;
bool isWarm = false;
bool goForSwim = isSunny && isWarm; // goForSwim is false
bool stayIndoors = !goForSwim; // stayIndoors is true
Sample Code
Let's see an example of using these operators in C++:
#include <iostream>
using namespace std;
int main() {
int num1 = 10;
int num2 = 5;
bool isTrue = true;
bool isFalse = false;
int sum = num1 + num2;
bool isEqual = (num1 == num2);
bool isLogicalAnd = (isTrue && isFalse);
bool isLogicalOr = (isTrue || isFalse);
bool isLogicalNot = !isTrue;
cout << "Sum: " << sum << endl;
cout << "Is Equal? " << isEqual << endl;
cout << "Logical AND: " << isLogicalAnd << endl;
cout << "Logical OR: " << isLogicalOr << endl;
cout << "Logical NOT: " << isLogicalNot << endl;
return 0;
}
In this code, we've used various arithmetic, comparison, and logical operators to perform operations and comparisons.
Conclusion
Understanding and using operators in C++ is fundamental to programming. They allow you to manipulate data, make decisions, and control the flow of your program. As you continue your C++ journey, you'll discover more complex operator usage and applications.