Operators in C++: Arithmetic, Logical, Relational

Operators in C++: Arithmetic, Logical, and Relational form the backbone of any C++ program, helping you perform a wide array of operations effortlessly. Whether you’re crunching numbers, making decisions, or comparing data, understanding these operators is crucial. Not sure where to start or looking to brush up on your skills? Dive in, and let’s explore the fascinating world of C++ operators together! By the end of this, you’ll be coding with more confidence and efficiency. Ready? Let’s go!

What are Operators in C++?

Operators in C++ are special symbols or keywords used to perform specific operations on one or more values, known as operands. These operations can range from basic mathematical calculations to complex logical comparisons and data manipulations.

Operators form the foundation of any C++ program. They help in executing tasks like addition, checking conditions, or combining multiple conditions to make decisions.

How Operators Work with Operands

Operators act upon operands, which are the variables or values on which the operation is performed. For example, in the expression a + b, the operator + adds the operands a and b.

Each operator follows specific rules about how it interacts with operands:

  • Some operators need two operands (binary operators), like a * b.
  • Some work with one operand (unary operators), like ++a.
  • Others may involve three operands (ternary operator), like condition ? value1 : value2.

Types of Operators in C++

C++ provides a variety of operators, each serving different purposes. The major categories include:

  1. Arithmetic Operators – For mathematical operations (+, -, *, /, %)
  2. Relational Operators – For comparing values (==, !=, >, <, etc.)
  3. Logical Operators – For combining conditions (&&, ||, !)
  4. Assignment Operators – For assigning values (=, +=, -=, etc.)
  5. Bitwise Operators – For bit-level operations (&, |, ^, <<, >>)
  6. Unary Operators – Work with a single operand (++, --, -, !)
  7. Ternary Operator – Conditional operator (? :)
  8. Other Operators – Like sizeof, pointer-related operators (*, &), and more

3. Arithmetic Operators in C++

Explanation:

Arithmetic operators in C++ are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These are essential for handling calculations in any C++ program and are commonly used in loops, formulas, and logic implementations.

List of Arithmetic Operators:

OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (remainder)
++Increment
--Decrement

Syntax and Examples:

#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 3;

    cout << "Addition: " << (a + b) << endl;      // Output: 13
    cout << "Subtraction: " << (a - b) << endl;   // Output: 7
    cout << "Multiplication: " << (a * b) << endl; // Output: 30
    cout << "Division: " << (a / b) << endl;      // Output: 3
    cout << "Modulus: " << (a % b) << endl;       // Output: 1

    a++;
    cout << "Incremented a: " << a << endl;       // Output: 11

    b--;
    cout << "Decremented b: " << b << endl;       // Output: 2

    return 0;
}

Use Cases:

  • Calculating totals, averages, or percentages
  • Implementing counters and loops
  • Performing mathematical logic in finance, games, or physics engines
  • Handling formulas in scientific or statistical applications

4. Relational Operators in C++

Explanation:

Relational operators are used to compare two values. The result of a relational operation is either true or false, which is commonly used in control statements like if, while, or for loops to guide the program flow.

List of Relational Operators:

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Syntax and Examples:

#include <iostream>
using namespace std;

int main() {
    int x = 5, y = 10;

    if (x == y)
        cout << "x is equal to y" << endl;
    if (x != y)
        cout << "x is not equal to y" << endl;
    if (x < y)
        cout << "x is less than y" << endl;
    if (y > x)
        cout << "y is greater than x" << endl;
    if (x <= 5)
        cout << "x is less than or equal to 5" << endl;
    if (y >= 10)
        cout << "y is greater than or equal to 10" << endl;

    return 0;
}

Use Cases:

  • Conditional checks in authentication systems (e.g., password length, age eligibility)
  • Decision-making in games (e.g., checking scores or health points)
  • Filtering data in loops (e.g., selecting numbers greater than a threshold)
  • Implementing validations and constraints in user input or forms

5. Logical Operators in C++

Explanation:

Logical operators in C++ are used to combine two or more conditions and return a boolean result (true or false). These are especially useful when decision-making depends on multiple conditions being true, false, or a combination of both.

List of Logical Operators:

OperatorNameDescription
&&Logical ANDReturns true if both conditions are true
``
!Logical NOTReverses the result of the condition

Syntax and Examples:

#include <iostream>
using namespace std;

int main() {
    int age = 20;
    int score = 85;

    // Logical AND
    if (age >= 18 && score > 80) {
        cout << "Eligible for advanced level" << endl;
    }

    // Logical OR
    if (age < 18 || score > 90) {
        cout << "Special consideration granted" << endl;
    }

    // Logical NOT
    bool registered = false;
    if (!registered) {
        cout << "Please register to continue" << endl;
    }

    return 0;
}

Use Cases:

  • Validating user input (e.g., form fields not empty and valid format)
  • Complex conditional logic in games or simulations
  • Role-based access control (e.g., check if user is admin or editor)
  • Filtering data based on multiple criteria

Comparison Table of Arithmetic vs Relational vs Logical Operators

FeatureArithmetic OperatorsRelational OperatorsLogical Operators
PurposePerform mathematical calculationsCompare valuesCombine or invert conditions
Operator Symbols+, -, *, /, %, ++, --==, !=, >, <, >=, <=&&, `
Common Use CaseCalculating totals, scores, loopsValidating equality or rangeChecking multiple conditions
Exampletotal = a + b;if (x >= 18)if (age > 18 && score > 80)

Applying C++ Operators in Real-Life Coding Scenarios

  1. Financial Calculations: Imagine a bank using C++ to develop software for calculating interest, processing loan repayments, and managing customer balances. They’d rely heavily on arithmetic operators (+, -, *, /) for these calculations, ensuring accurate financial operations.
  2. Inventory Management: A retail company could use relational operators (<, >, ==) to keep track of inventory levels. By setting conditions, they can automatically trigger notifications when stock runs low, ensuring seamless supply chain management.
  3. Gaming Development: In creating a video game, developers might use logical operators (&&, ||, !) to manage game logic. For example, determining if a character unlocks a level would involve checking multiple conditions, like having completed previous levels and achieved a certain score.
  4. Data Analysis: A company focused on data analytics might employ a mix of these operators to sift through large datasets. They can efficiently filter out relevant data using conditions and arithmetic calculations, facilitating better decision-making.
  5. Weather Forecasting: Meteorological software might use C++ to predict weather patterns. Relational operators help compare temperature and pressure readings to historical data, while logical operators ensure accurate predictions by combining multiple climatic conditions.

7. Common Mistakes to Avoid

Understanding operators is crucial, but even experienced programmers sometimes make avoidable errors. Here are some of the most common mistakes:

1. Confusing = with ==

  • = is the assignment operator, while == checks for equality.
  • Wrong: if (a = 5) → assigns 5 to a, always evaluates to true.
  • Correct: if (a == 5) → checks if a is equal to 5.

2. Using Logical Operators with Non-Boolean Values

  • Logical operators (&&, ||, !) are meant for boolean expressions.
  • Misusing them with integers or uninitialized variables may lead to unexpected results.

3. Integer Division Issues in Arithmetic Operations

  • In C++, dividing two integers results in an integer (decimal part is discarded).
  • Example: 5 / 2 results in 2, not 2.5.
  • To avoid this, cast one operand to float: (float)5 / 2 gives 2.5.

8. Practice Questions

Test your understanding with these short exercises:

1. Output Prediction

int a = 10, b = 3;
cout << a / b;

Q: What will be the output?

a) 3.33
b) 3
c) 3.0
d) Error

2. Identify the Mistake

int age = 18;
if (age = 18) {
    cout << "Adult";
}

Q: What is wrong with this code?

3. Logical Operator Evaluation

int x = 5, y = 10;
if (x > 2 && y < 15) {
    cout << "Valid";
}

Q: Will “Valid” be printed?

a) Yes
b) No
c) Depends on compiler
d) Syntax Error

4. Fix the Code

int a = 5;
if (!a == 5) {
    cout << "True";
}

Q: What should be corrected for the condition to properly check if a is not equal to 5?

5. Write a Condition

Write an if statement that checks:

  • Age is greater than or equal to 18
  • Score is more than 75

Expected Output: “Qualified for the exam.”

    Our AI-powered cpp online compiler lets users instantly write, run, and test their code seamlessly. With AI integration, it simplifies the coding process, enabling quick corrections and optimisations. It’s perfect for learners and developers who want an efficient, user-friendly tool to enhance their C++ programming skills.

    Conclusion

    Completing ‘Operators in C++: Arithmetic, Logical, and Relational’ empowers you with fundamental programming skills that are crucial for problem-solving. By understanding these operators, you’re set to tackle complex challenges confidently. Ready to elevate your coding game? Explore more programming languages like Java, Python, and more on Newtum.

    Edited and Compiled by

    This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.

    About The Author