For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
When you're diving into C programming, one concept you’ll encounter early on is the relational operator in C. These operators are the backbone of decision-making in your programs. Whether you're writing a simple conditional check or a complex control flow, understanding how relational operators work can make your code not only correct but also efficient and clean.
In this blog, we’re going to explore relational operators in C from the ground up. We’ll explain what they are, look at the various types, work through detailed code examples (with output and explanations), and even touch on best practices for using them effectively in real-world C programs.
By the end of this guide, you’ll have a solid grip on relational operators in C—how to use them, when to use them, and how to avoid common mistakes. Whether you're a beginner just learning the ropes or someone brushing up your knowledge, you’ll also find the UpGrad’s software development courses really helpful.
But, before you begin with this topic, it’s recommended to understand the operators in C language.
A relational operator in C is used to compare two values or expressions. The result of such a comparison is always a Boolean value in C: either true (represented as 1) or false (represented as 0). These operators are fundamental in writing conditional logic, especially within control structures such as if, while, and for.
When you write a condition like “is A greater than B?”, you’re using a relational operator in C. These operators help your program make decisions by evaluating the relationship between variables or values.
Here is a summary of all the relational operators available in the C programming language:
Operator Name | Symbol | Description | Example |
Equal to | == | Checks if two values are equal | a == b |
Not equal to | != | Checks if two values are not equal | a != b |
Greater than | > | Checks if the left value is greater | a > b |
Less than | < | Checks if the left value is smaller | a < b |
Greater than or equal to | >= | Checks if the left value is greater or equal | a >= b |
Less than or equal to | <= | Checks if the left value is smaller or equal | a <= b |
Boost your career journey with the following full-stack development courses:
Each relational operator in C is designed to return a simple yes-or-no answer, which is then used to determine how the program should proceed. These comparisons form the basis for logical decisions throughout your code.
Whether you're building loops, filtering data, or implementing complex control structures, you’ll rely on the relational operator in C to make your logic work correctly and predictably.
In addition to this, there are many other types of operators in C, such as:
C provides six types of relational operators in C that allow you to compare values and control program flow. Let’s explore each one in detail.
The `==` relational operator in C checks whether two values are equal. It's commonly used in conditional statements where an action is taken only if a specific condition holds true. This operator compares both operands and returns true if they are equal.
Syntax:
operand1 == operand2
Code Example:
#include <stdio.h>
int main() {
int a = 5, b = 5;
// Using '==' to check if a is equal to b
if (a == b) {
printf("a is equal to b\n");
} else {
printf("a is not equal to b\n");
}
return 0;
}
Output:
a is equal to b
Explanation:
In this example, the `==` relational operator in C returns true because both `a` and `b` have the same value.
Furthermore, this relational operator in C is also used to develop a C program to find the leap year.
The `!=` relational operator in C is used to determine if two values are different. It returns true when the operands are not equal, and false otherwise. This is particularly useful when checking for conditions that must not be true.
Syntax:
operand1 != operand2
Code Example:
#include <stdio.h>
int main() {
int x = 10, y = 20;
// Using '!=' to check if x is not equal to y
if (x != y) {
printf("x is not equal to y\n");
} else {
printf("x is equal to y\n");
}
return 0;
}
Output:
x is not equal to y
Explanation:
Here, the `!=` relational operator in C evaluates to true because `x` and `y` are not equal.
The `>` relational operator in C is used to check if the left operand is strictly greater than the right operand. This operator is useful when filtering or validating data ranges.
Syntax:
operand1 > operand2
Code Example:
#include <stdio.h>
int main() {
int m = 25, n = 15;
// Using '>' to check if m is greater than n
if (m > n) {
printf("m is greater than n\n");
} else {
printf("m is not greater than n\n");
}
return 0;
}
Output:
m is greater than n
Explanation:
The `>` relational operator in C evaluates this expression to true because 25 is greater than 15.
Apart from relational operators in C, you should also learn about the if-else statement to develop efficient code logics.
The `<` relational operator in C checks whether the left-hand operand is strictly less than the right-hand operand. It is especially useful in loops and conditional logic where a lower boundary must be enforced.
Syntax:
operand1 < operand2
Code Example:
#include <stdio.h>
int main() {
int a = 8, b = 12;
// Using '<' to check if a is less than b
if (a < b) {
printf("a is less than b\n");
} else {
printf("a is not less than b\n");
}
return 0;
}
Output:
a is less than b
Explanation:
Since 8 is less than 12, the `<` relational operator in C evaluates this condition to true.
The `>=` relational operator in C returns true if the left operand is greater than or equal to the right operand. This is helpful when checking for minimum threshold values or validating input boundaries.
Syntax:
operand1 >= operand2
Code Example:
#include <stdio.h>
int main() {
int score = 70, pass_mark = 60;
// Using '>=' to check if score is enough to pass
if (score >= pass_mark) {
printf("Score is enough to pass\n");
} else {
printf("Score is below the passing mark\n");
}
return 0;
}
Output:
Score is enough to pass
Explanation:
The `>=` relational operator in C evaluates this condition as true because 70 is greater than 60.
The `<=` relational operator in C checks if the left operand is less than or equal to the right operand. It is frequently used to set upper limits in conditional checks.
Syntax:
operand1 <= operand2
Code Example:
#include <stdio.h>
int main() {
int limit = 100, usage = 100;
// Using '<=' to check if usage is within the limit
if (usage <= limit) {
printf("Usage is within the limit\n");
} else {
printf("Usage exceeds the limit\n");
}
return 0;
}
Output:
Usage is within the limit
Explanation:
Here, the `<=` relational operator in C evaluates to true because `usage` equals `limit`.
Each relational operator in C helps developers implement logic that reacts to comparisons. Whether you're checking user input, controlling loops, or making decisions in complex systems, these operators form a fundamental part of your C programming toolkit.
Also read about the types of errors in C to quickly troubleshoot your C programs.
In this section, we will explore some practical examples of relational operators in C in action. These examples will help you see how different relational operators can be used in real-world programming scenarios.
This example demonstrates how to use relational operators in C to compare user input with predefined values.
#include <stdio.h>
int main() {
int enteredAge, requiredAge = 18;
// Prompt user for age input
printf("Please enter your age: ");
scanf("%d", &enteredAge);
// Check if the user is old enough to vote
if (enteredAge >= requiredAge) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
Output (if age entered is 20):
You are eligible to vote.
Explanation:
In this program, the `>=` relational operator checks whether the entered age is greater than or equal to the required age of 18. If the condition is true, the user is informed that they are eligible to vote.
Here’s an example where we use relational operators in C to sort three numbers in ascending order. This is a common scenario in algorithms, such as bubble sort or selection sort.
#include <stdio.h>
int main() {
int num1, num2, num3;
// User inputs three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Sorting the numbers in ascending order using relational operators
if (num1 > num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 > num3) {
int temp = num1;
num1 = num3;
num3 = temp;
}
if (num2 > num3) {
int temp = num2;
num2 = num3;
num3 = temp;
}
// Output the sorted numbers
printf("The numbers in ascending order are: %d, %d, %d\n", num1, num2, num3);
return 0;
}
Output (if numbers entered are 34, 12, and 56):
The numbers in ascending order are: 12, 34, 56
Explanation:
In this example, we use the `>` relational operator in C to compare the numbers and swap them accordingly. The numbers are sorted by checking pairs, ensuring that the smallest number is placed first.
To develop such programs, you must go through our article on nested if-else statements in C.
This example shows how relational operators in C can be used to check if a value lies within a specific range, such as determining if a number falls within a valid range for a certain process.
#include <stdio.h>
int main() {
int number;
// Prompt the user to enter a number
printf("Enter a number between 1 and 100: ");
scanf("%d", &number);
// Check if the number is within the valid range
if (number >= 1 && number <= 100) {
printf("The number %d is within the valid range.\n", number);
} else {
printf("The number %d is outside the valid range.\n", number);
}
return 0;
}
Output (if number entered is 50):
The number 50 is within the valid range.
Explanation:
In this case, the `>=` and `<=` relational operators in C are used to check if the entered number lies between 1 and 100, inclusive. If it does, the program prints that the number is within the valid range.
In C, strings are often compared using relational operators to check if one string is lexicographically greater than another. Here’s an example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
// Get two strings from the user
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
// Compare the strings using relational operators
if (strcmp(str1, str2) == 0) {
printf("Both strings are equal.\n");
} else if (strcmp(str1, str2) > 0) {
printf("The first string is lexicographically greater.\n");
} else {
printf("The second string is lexicographically greater.\n");
}
return 0;
}
Output
(if `str1 = "apple"` and `str2 = "banana"`):
The second string is lexicographically greater.
Explanation:
The `strcmp()` function compares the two strings. The result of `strcmp(str1, str2)` is used with the `==`, `>` relational operators in C to determine which string is greater or if they are equal.
This example demonstrates how relational operators in C can be used within loops to control repetition. In this case, a `while` loop is used to ensure the user enters a valid age within a certain range.
#include <stdio.h>
int main() {
int age;
// Keep prompting the user until they enter a valid age
do {
printf("Enter your age (between 18 and 99): ");
scanf("%d", &age);
} while (age < 18 || age > 99); // Using relational operators to check the range
printf("You entered a valid age: %d\n", age);
return 0;
}
Output (if user enters 16, then 25):
Enter your age (between 18 and 99): 16
Enter your age (between 18 and 99): 25
You entered a valid age: 25
Explanation:
The `while` loop continues until the user enters a valid age (between 18 and 99). The relational operators `<` and `>` are used to enforce the boundaries.
These examples demonstrate how the various relational operators in C can be used for different logical conditions, comparisons, and validations in real-world scenarios. Understanding these operators and how they work is crucial for writing efficient, decision-making code.
Following are the top five best practices to follow while using relational operators in C.
When working with relational operators, avoid comparing a variable to itself or using unnecessary conditions that are always true or false. For instance, comparing `a == a` is redundant, as it will always return true. These types of comparisons can clutter your code and may confuse other developers, leading to potential mistakes when maintaining the code.
It’s important to be mindful of operator precedence when using relational operators. Always use parentheses to group conditions when combining relational operators with logical operators like `&&` (AND) or `||` (OR). Without parentheses, C's operator precedence can lead to unexpected results, especially in complex conditions, making your code harder to understand and maintain.
When you need to check multiple conditions in a single `if` or `while` statement, use logical AND (`&&`) or OR (`||`) to combine relational expressions. This allows you to avoid unnecessary nested `if` statements and makes the code more concise and easier to read.
A common use of relational operators is checking if a value falls within a specified range. For example, when validating user input (like checking if an age is between 18 and 99), combining relational operators like `>=` and `<=` ensures clarity and efficiency in your conditions.
Always ensure that the data types of the operands being compared are compatible. For instance, comparing an integer with a floating-point value can lead to unexpected results due to type promotion. Ensuring correct data types prevents errors and improves the reliability of the comparison, making the code more robust.
By following these best practices, you can use relational operators in C effectively and write clean, understandable, and bug-free code.
In conclusion, relational operators in C are crucial tools for making comparisons and controlling the flow of a program. They allow developers to perform logical comparisons between values and execute specific actions based on these conditions. Understanding how and when to use these operators is fundamental for any C programmer.
Throughout this blog, we've explored the six types of relational operators in C: ==, !=, >, <, >=, and <=. We've also seen how they can be applied in real-world scenarios, from comparing user inputs to sorting data and implementing complex conditions. Additionally, best practices like avoiding redundant comparisons, being mindful of operator precedence, and ensuring proper data types help keep the code clean and error-free.
By mastering the usage of relational operators in C, you can make your code more efficient, readable, and maintainable. Whether you're building small programs or working on larger systems, these operators will always be an essential part of your toolkit.
1. What are relational operators in C?
Relational operators in C are used to compare two values or variables. They allow programmers to check conditions like equality, inequality, or magnitude. The six main relational operators in C are `==`, `!=`, `>`, `<`, `>=`, and `<=`. They return a boolean result (`true` or `false`), which is used in decision-making and control structures.
2. How many relational operators are there in C?
C has six relational operators: `==` (equal to), `!=` (not equal to), `>` (greater than), `<` (less than), `>=` (greater than or equal to), and `<=` (less than or equal to). These operators help compare two operands and return a boolean result, aiding in logical comparisons within conditional statements like `if` or loops.
3. What does the '==' operator do in C?
The `==` operator in C checks whether two values are equal. It compares the left and right operands and returns `true` (1) if they are equal, and `false` (0) if they are not. It is crucial to distinguish `==` from `=`, the assignment operator, which is used to assign a value to a variable.
4. What is the difference between '==' and '!=' in C?
The `==` operator checks for equality between two operands, returning `true` if they are equal. On the other hand, the `!=` operator checks for inequality, returning `true` if the operands are not equal. Both are commonly used in conditional expressions to control the flow of the program based on comparisons.
5. How does the '>' operator work in C?
The `>` operator in C is used to check if the left operand is greater than the right operand. If the condition is true, it returns `true` (1); otherwise, it returns `false` (0). This operator is useful for numerical comparisons, like determining if a number exceeds a certain threshold in loops or conditions.
6. When should I use the '<' relational operator in C?
The `<` operator in C is used to check if the left operand is less than the right operand. It’s helpful in situations where you need to determine if a value falls below a specified threshold, such as comparing ages, scores, or other measurements. It returns `true` (1) if the condition is met, otherwise `false` (0).
7. Can I use relational operators to compare floating-point numbers in C?
Yes, you can use relational operators to compare floating-point numbers in C, but with caution. Floating-point numbers may have precision issues, so comparisons involving them could yield inaccurate results. For more precise comparisons, consider using a small tolerance value, ensuring the difference between numbers is within an acceptable range rather than directly comparing them.
8. What happens if I use relational operators with mismatched data types in C?
If relational operators are used with mismatched data types, C will automatically convert one of the operands to a compatible type. For example, comparing an integer with a float will result in the integer being converted to a float. However, such conversions may lead to loss of precision or unexpected results, so it’s important to ensure compatible data types.
9. How do relational operators impact conditional statements in C?
Relational operators are used in conditional statements, like `if`, `while`, or `for`, to evaluate the truth of a condition. Depending on the result of the relational comparison, the program either executes or skips certain blocks of code. These operators are crucial for controlling the program flow based on specific conditions, such as equality or range checks.
10. Can I combine multiple relational operators in a single expression in C?
Yes, multiple relational operators can be combined in a single expression using logical operators like `&&` (AND) or `||` (OR). This allows complex comparisons where you check multiple conditions at once. For example, you could check if a number is both greater than 10 and less than 100 by combining `>` and `<` relational operators.
11. What are the best practices for using relational operators in C?
When using relational operators, avoid unnecessary comparisons like comparing a variable to itself. Always use parentheses to clarify the order of evaluation in complex conditions, and ensure you are using compatible data types. Additionally, combine relational operators effectively to minimize nested conditions and improve code readability. Using relational operators thoughtfully will help avoid bugs and improve efficiency.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.