Comparison operators
Comparison operators are used to compare two values and return a boolean result (true or false).
They are fundamental in programming for making decisions and controlling the flow of execution.
Here are those:
Equal to (==)
Purpose: Checks if the two values are equal.
Syntax: a == b
Example:
int a = 5;
int b = 5;
if (a == b) {
// This block will execute code because a is equal to b
}
Not equal to (!=)
Purpose: Checks if the two values are not equal.
Syntax: a != b
Example:
int a = 5;
int b = 3;
if (a != b) {
// This block will execute code because a is not equal to b
}
Greater than (>)
Purpose: Checks if the value on the left is greater than the value on the right.
Syntax: a > b
Example:
int a = 5;
int b = 3;
if (a > b) {
// This block will execute because a is greater than b
}
Less than (<)
Purpose: Checks if the value on the left is less than the value on the right.
Syntax: a < b
Example:
int a = 3;
int b = 5;
if (a < b) {
// This block will execute because a is less than b
}
Greater than or equal to (>=)
Purpose: Checks if the value on the left is greater than or equal to the value on the right.
Syntax: a >= b
Example:
int a = 5;
int b = 5;
if (a >= b) {
// This block will execute because a is equal to b
}
Less than or equal to (<=)
Purpose: Checks if the value on the left is less than or equal to the value on the right.
Syntax: a <= b
Example:
int a = 3;
int b = 5;
if (a <= b) {
// This block will execute because a is less than b
}
Practical Applications
Conditional Statements
Conditional statements will be explained in upcoming blog .
Comparison operators are commonly used in conditional statements to control the flow of execution.
Example:
#include <iostream>
using namespace std ;
int age = 18;
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
In this example:
The condition age >= 18
checks if the value of age is greater than or equal to 18.
The appropriate message is printed based on the result of the comparison.
Loops
Loops will be explained in upcoming blog .
Comparison operators are also used in loops to determine the continuation or termination of the loop.
Example:
for (int i = 0; i < 10; i++) {
printf("%d ", i); // Prints numbers from 0 to 9
}
Top comments (0)