Comparing Values

Before a program can make a choice, it must ask a question like "is the age at least 18?". We ask these questions with comparison operators:

OperatorMeansExampleAnswer
==is equal to5 == 5true (1)
!=is not equal to5 != 3true (1)
<is less than2 < 1false (0)
>is greater than9 > 4true (1)
<=is less than or equal to3 <= 3true (1)
>=is greater than or equal to2 >= 8false (0)

In C, a comparison gives back a number: 1 for true and 0 for false:

#include <stdio.h>

int main() {
    int age = 20;
    printf("%d\n", age >= 18);
    printf("%d\n", age == 30);
    printf("%d\n", age != 30);
    return 0;
}

Output

1
0
1

Common mistake: Mixing up = and ==. One = puts a value in a variable. Two == ask whether two values are equal.

Think of it like this: = is like saying "the box now holds 5". == is like asking "does the box hold 5?"

HOME LABS COMMUNITY DASHBOARD