Skip to main content

Relational and assignment operators

Short answer

Relational operators compare values (e.g., a>b returns 1 or 0). Assignment operators include = and compound forms: +=, -=, *=, /=, %=, which combine operation and assignment. For example, x += 5 is equivalent to x = x + 5.

What are relational operators and assignment operators? Explain with examples.

Relational operators (<, <=, >, >=, ==, !=) compare two operands and give 1 if the relation is true, otherwise 0. They are used in conditions of if and loops, for example a > b.

Assignment operators store a value in a variable. The basic one is =; the compound ones (+=, -=, *=, /=, %=) combine an operation with assignment: x += 5 means x = x + 5.

Example:

#include <stdio.h>
int main(void)
{
    int x = 10;
    x += 5;  printf("x += 5  -> %d\n", x);
    x -= 3;  printf("x -= 3  -> %d\n", x);
    x *= 2;  printf("x *= 2  -> %d\n", x);
    x /= 4;  printf("x /= 4  -> %d\n", x);
    x %= 4;  printf("x %%= 4  -> %d\n", x);
    printf("x == 2 gives %d, x > 5 gives %d\n", x == 2, x > 5);
    return 0;
}

Output:

x += 5  -> 15
x -= 3  -> 12
x *= 2  -> 24
x /= 4  -> 6
x %= 4  -> 2
x == 2 gives 1, x > 5 gives 0

Note that = assigns while == compares.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 3 questions →