0
0
Cprogramming~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, like if one is bigger, smaller, or equal to the other.
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.
Deciding if a score is high enough to pass a test.
Stopping a loop when a condition is no longer true.
Syntax
C
expression1 operator expression2
expression1 and expression2 are values or variables you want to compare.
operator can be one of: ==, !=, >, <, >=, <=.
Examples
Checks if a is equal to b.
C
if (a == b) { /* code */ }
Checks if x is not equal to y.
C
if (x != y) { /* code */ }
Checks if score is greater than or equal to 50.
C
if (score >= 50) { /* code */ }
Checks if age is less than 18.
C
if (age < 18) { /* code */ }
Sample Program
This program compares two numbers using relational operators and prints messages based on the comparisons.
C
#include <stdio.h>

int main() {
    int a = 10;
    int b = 20;

    if (a < b) {
        printf("a is less than b\n");
    }

    if (a != b) {
        printf("a is not equal to b\n");
    }

    if (b >= 20) {
        printf("b is greater than or equal to 20\n");
    }

    if (a == 10) {
        printf("a is equal to 10\n");
    }

    return 0;
}
OutputSuccess
Important Notes
Relational operators always return 1 (true) or 0 (false) in C.
Use double equals (==) to check equality, not a single equals (=) which is for assignment.
Be careful with operator precedence when combining multiple conditions.
Summary
Relational operators compare two values and return true or false.
They are useful for making decisions in your program.
Common operators include ==, !=, >, <, >=, and <=.