Skip to main content

Conditional Statements

Sometimes a program needs to make a decision and change its behavior accordingly.

Example​

Is the password correct?

The answer is either true or false, and the program should react differently:

  • If true, display "Access Granted!"
  • If false, display "Access Denied"

To do this, we use comparison and logical operators to ask yes/no questions, then use conditional statements to change the program's behavior based on that answer.

if Statements​

if (condition)
{
// runs if condition is true
}
// code after if
  • If condition is true, the code inside {} runs.
  • If condition is false, that code is skipped, and execution continues after the block.

Examples​

I should wear a jacket IF its cold OR it's raining.

double temp = 10;
bool isRaining = true;

if (temp < 5.0 || isRaining)
{
Console.WriteLine("🧥");
}

I can drive IF i have a license AND I am above the legal driving age.

bool hasLicense = true;
int age = 20;

if (age >= 16 && hasLicense)
{
Console.WriteLine("🚗 toot toot");
}

I can eat the cookie IF it's NOT expired.

bool isExpired = false;

if (!isExpired)
{
Console.WriteLine("🍪 miam");
}

Note the variable is named isExpired, not notExpired. Why? negating notExpired (!notExpired, "not not expired") gets confusing fast. Only name booleans for their positive case.

Bad Conditions​

int a = 2;
int b = 4;

if (a < b)
Console.WriteLine("yes");
Console.WriteLine("hello world");
Console.WriteLine("All done!");

It looks like both Console.WriteLine calls belong to the if, but without {}, only the line directly after if is part of it.

Therefore, this code is actually equivalent to:

int a = 2;
int b = 4;

if (a < b)
Console.WriteLine("yes");
Console.WriteLine("hello world");
Console.WriteLine("All done!");

This still compiles, but it's a bug waiting to happen. If a programmer adds a line assuming it's inside the if block, it'll break the program.

SO Always use braces, even for single line blocks:

int a = 2;
int b = 4;

if (a < b)
{
Console.WriteLine("yes");
}
Console.WriteLine("hello world");
Console.WriteLine("All done!");