Comparison Operators

Learn how comparison operators work in C. We cover each operator step by step with clear examples on Debian 12 using Vim.

Understanding Comparison Operators in C

Comparison operators are used in C to compare values. They return either true (1) or false (0), making them essential for decision-making in programs.

What Are Comparison Operators?

Comparison operators test relationships between two values. They are often used in conditional statements like if-else and loops.

  • == (Equal to): Returns true if both values are the same.
  • != (Not equal to): Returns true if the values are different.
  • > (Greater than): True if the left value is larger.
  • < (Less than): True if the left value is smaller.
  • >= (Greater than or equal to): True if the left value is larger or equal.
  • <= (Less than or equal to): True if the left value is smaller or equal.

Declaring Variables

We need two variables for comparison.

int a = 10;
int b = 20;

Example Program: Comparison Operators

This C program shows each comparison operator in action and prints the results.

#include 

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

    printf(\\"a == b: %d\\\
\\", a == b);
    printf(\\"a != b: %d\\\
\\", a != b);
    printf(\\"a > b: %d\\\
\\", a > b);
    printf(\\"a < b: %d\\\
\\", a < b);
    printf(\\"a >= b: %d\\\
\\", a >= b);
    printf(\\"a <= b: %d\\\
\\", a <= b);

    return 0;

Step-by-Step Explanation

  • a == b: Checks if 10 equals 20. False (0).
  • a != b: Checks if 10 does not equal 20. True (1).
  • a > b: Checks if 10 is greater than 20. False (0).
  • a < b: Checks if 10 is less than 20. True (1).
  • a >= b: Checks if 10 is greater than or equal to 20. False (0).
  • a <= b: Checks if 10 is less than or equal to 20. True (1).

Compiling and Running

To compile and run the program on Debian 12:

gcc comparison.c -o comparison
./comparison

Expected Output

a == b: 0
a != b: 1
a > b: 0
a < b: 1
a >= b: 0
a <= b: 1

Why Learn Comparison Operators?

Comparison operators let your program make decisions. They are essential for conditions, loops, and validating data.

Conclusion

Mastering comparison operators will help you build dynamic and responsive C programs. Practice using them with different values and conditions.

Subscribe to Our YouTube for More

Download as PDF

https://blog.arashtad.com/updates/comparison-operators/?feed_id=12296&_unique_id=6883370546727

Comments

Popular posts from this blog

Why Smart Contracts Are Revolutionary? (Smart Contracts Use Cases)

A Quick Guide to Tron Network Interaction using Python.

WordPress: The best CMS platform to create website