Skip to content

Conditions

The Course
•
25 min study

Programs so far have done the same thing every time. An if statement runs a block only when a condition is true. The optional else block runs when it isn't. Conditions go in parentheses, and braces mark the block.

A condition must be a bool. You can get one from a comparison: == (equal), != (not equal), <, <=, > and >=. Remember that = stores a value and == compares two values. In C#, if (minutes = 10) is a compile error, which saves you from a classic bug in other languages.

Which block runs? C#
int minutes = 25;

if (minutes >= 30)
{
    Console.WriteLine("Long session");
}
else
{
    Console.WriteLine("Short session");
}

Console.WriteLine("Always printed");
Check your prediction
Text
Short session
Always printed

Try 30 and 31. A rule like "at least 30" has an edge, and the edge is where mistakes live, so test exactly on it.

Chains check from the top

else if adds more cases. C# tests them in order and runs only the first block whose condition is true, then skips the rest of the chain. That means later conditions can rely on earlier ones having failed.

The first match wins C#
int score = 75;

if (score >= 50)
{
    Console.WriteLine("Pass");
}
else if (score >= 70)
{
    Console.WriteLine("Good");
}
else
{
    Console.WriteLine("Try again");
}
Check your prediction
Text
Pass

That is probably not what the author meant, because no score can ever reach Good: anything 70 or above has already matched the first test. Reorder the conditions so the most specific comes first, then test 75, 50 and 49.

Combining facts

&& means both sides must be true. || means at least one side must be true, including when both are. ! flips a bool. Use parentheses when you mix them, so nobody has to remember the precedence.

Inside and outside a range C#
int minutes = 200;
bool hasTime = true;

Console.WriteLine(minutes >= 1 && minutes <= 180);
Console.WriteLine(minutes < 1 || minutes > 180);
Console.WriteLine(!hasTime);
Console.WriteLine(minutes <= 180 || hasTime);
Check your prediction
Text
False
True
False
True

You can't shorten a range to 1 <= minutes <= 180 as you might in maths; that's an error here. Each side of && must be a complete comparison.

The second side may not run

C# stops as soon as it knows the answer. In a && b, if a is false then b is never evaluated. This is called short-circuiting, and you can use it to guard a risky operation. Dividing an int by zero crashes a program, so the check goes first.

A guard before dividing C#
int total = 30;
int count = 0;

if (count != 0 && total / count > 10)
{
    Console.WriteLine("High average");
}
else
{
    Console.WriteLine("No high average");
}
Check your prediction
Text
No high average

Swap the two sides of &&, and predict what happens before you run it. Then restore the safe order.

Your turn

Exercise

Check a session

A session is valid when minutes is from 1 to 180 inclusive. Print Invalid for anything else. For valid sessions, print Long when minutes is 60 or more, and Short otherwise. Test with 0, 1, 59, 60, 180 and 181.

Your workspace C#
int minutes = 60;
Console.WriteLine(minutes);
Hint 1: the idea

Rule out invalid values first. Then the later branches only ever see valid values.

Hint 2: a first step

Write the invalid test using ||, with one comparison for each side of the allowed range.

Show one solution
C#
int minutes = 60;

if (minutes < 1 || minutes > 180)
{
    Console.WriteLine("Invalid");
}
else if (minutes >= 60)
{
    Console.WriteLine("Long");
}
else
{
    Console.WriteLine("Short");
}
Text
Long

The invalid case is checked first. If >= 60 came first, a value of 500 would be called Long instead of Invalid. else if means only one branch runs, and the final else catches everything the earlier tests didn't, so every number gets exactly one answer.

Change || to && in the solution and find a value that exposes the mistake. Why is no value both below 1 and above 180?

Was this article helpful?

Your response is saved on this device.