A program often needs to ask questions such as:
C# uses relational operators to compare values.
Common relational operators include:
> greater than
< less than
>= greater than or equal to
<= less than or equal toEach comparison produces:
trueor:
falseConsider:
homeScore > awayScoreIf:
homeScore = 3
awayScore = 1the expression evaluates to:
truebecause 3 is greater than 1.
You can use that result in an if statement:
if (homeScore > awayScore)
{
System.Console.WriteLine("Home team is ahead.");
}Suppose:
double distanceToBall = 4.5;The condition:
distanceToBall < 5.0asks:
If the answer is true, the controlled block runs.
Consider:
if (playerAge >= 18)
{
System.Console.WriteLine("Adult division.");
}The operator:
>=includes equality.
The condition is true when the age is greater than 18 or exactly 18.
For:
if (fouls <= 2)
{
System.Console.WriteLine("Within the current limit.");
}the expression is true when the value is below or equal to 2.
This:
homeScore > awayScoreis not an assignment.
It does not change either score.
It asks a question.
The result is a Boolean value:
trueor:
falseThat is why it can appear inside an if.
These are different questions:
score > 5
score >= 5If:
score = 5then the first expression is false and the second is true.
One symbol changes the boundary of the condition.
Suppose a requirement says:
The phrase:
at leastincludes 10 itself.
A fitting comparison is:
score >= 10Using:
score > 10would exclude the value 10 and would not match the requirement.
Whenever a condition uses a relational operator, identify the boundary.
For:
score >= 10the boundary is:
10Ask:
This habit helps prevent boundary mistakes.
Suppose:
public void DisplayScoreStatus(int score)
{
if (score >= 3)
{
System.Console.WriteLine("Three or more goals.");
}
}The parameter value becomes part of the Boolean expression.
The flow is:
For example:
int difference = homeScore - awayScore;
if (difference > 0)
{
System.Console.WriteLine("Home team is ahead.");
}The calculation happens first.
The comparison then asks a question about the calculated value.
This:
score == 5asks:
This:
score >= 5asks:
Choose based on the requirement.
A focused condition such as:
distanceToBall < 5.0communicates one clear question.
More complex combinations of several Boolean conditions are taught later.
For now, master one comparison at a time.
Relational operators turn numeric relationships into Boolean results: