0
0
C++programming~5 mins

Relational operators in C++

Choose your learning style9 modes available
Introduction

Relational operators help us compare two values to see how they relate to each other, like if one is bigger or smaller.

Checking if a number is greater than another to decide what to do next.
Comparing ages to see who is older.
Finding out if two values are equal before continuing a task.
Determining if a score is less than a passing mark.
Seeing if a temperature is within a safe range.
Syntax
C++
value1 < value2
value1 > value2
value1 <= value2
value1 >= value2
value1 == value2
value1 != value2

Use == to check if two values are equal, not = which assigns a value.

Relational operators return true or false (boolean values).

Examples
This checks if a is less than b. It is true because 5 is less than 10.
C++
int a = 5;
int b = 10;
bool result = a < b;  // true
This checks if x is equal to y. It is true because both are 7.
C++
int x = 7;
int y = 7;
bool result = x == y;  // true
This checks if m is not equal to n. It is true because 3 is not 8.
C++
int m = 3;
int n = 8;
bool result = m != n;  // true
Sample Program

This program compares two ages using relational operators and prints the results as 1 (true) or 0 (false).

C++
#include <iostream>
using namespace std;

int main() {
    int age1 = 20;
    int age2 = 25;

    cout << "Is age1 less than age2? " << (age1 < age2) << "\n";
    cout << "Is age1 equal to age2? " << (age1 == age2) << "\n";
    cout << "Is age1 not equal to age2? " << (age1 != age2) << "\n";

    return 0;
}
OutputSuccess
Important Notes

Relational operators always return a boolean value: true or false.

In C++, true prints as 1 and false prints as 0 when using cout.

Be careful to use == for comparison, not = which is for assignment.

Summary

Relational operators compare two values and return true or false.

They include <, >, <=, >=, ==, and !=.

Use them to make decisions based on how values relate to each other.