Virtual assistance Chat Bot

C Programming Tutorial

Welcome to AIVista --India's tutorial pages on C Programming

C Programming

Relational Operators in C

Relational operators are used to compare values and return boolean results (true or false).

"Relational operators are fundamental for decision-making and control structures in C."

What Are Relational Operators?

Relational operators compare two values and determine the relationship between them. They return either 1 (true) or 0 (false).

List of Relational Operators

Operator Description Example Result (if a = 10, b = 5)
== Equal to a == b 0 (false)
!= Not equal to a != b 1 (true)
> Greater than a > b 1 (true)
< Less than a < b 0 (false)
>= Greater than or equal to a >= b 1 (true)
<= Less than or equal to a <= b 0 (false)

Examples of Relational Operators

1. Basic Comparison Using Relational Operators

#include <stdio.h>

int main() {
int a = 10, b = 5;

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

return 0;
}

2. Using Relational Operators in Conditional Statements

#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);

if (age >= 18) {
	printf("You are eligible to vote.\n");
} else {
	printf("You are not eligible to vote.\n");
}

return 0;
}

3. Comparing Floating-Point Numbers

#include <stdio.h>

int main() {
float x = 3.5, y = 2.8;

printf("x == y: %d\n", x == y);
printf("x > y: %d\n", x > y);
printf("x < y: %d\n", x < y);

return 0;
}

Important Notes on Relational Operators

  • Comparison Result: The result is always either 1 (true) or 0 (false).
  • Floating-Point Comparison: Comparing floating-point values may lead to precision errors.
  • Difference Between = and ==: = is an assignment operator, while == is a comparison operator.

Best Practices for Using Relational Operators

  • Use == for equality checks and avoid using = by mistake.
  • Be cautious when comparing floating-point numbers due to precision issues.
  • Use relational operators in control statements like if, while, and for loops.

Example: Handling Floating-Point Precision Issues

#include <stdio.h>

int main() {
float a = 0.1, b = 0.2;

if ((a + b) == 0.3) {
	printf("Equal\n");
} else {
	printf("Not Equal (Precision Issue)\n");
}

return 0;
}

Conclusion

Relational operators are essential for comparing values and making decisions in C programs. Understanding their behavior will help in writing accurate and logical programs! 🚀