Five Minute C# — Lesson 5
Further conditional statements and their applications
Lessons: 1 ・ 2 ・ 3 ・ 4 ・ 5 ・ 6 ・ 7 ・ 8 ・ 9 ・ 10 ・ 11 ・ 12 ・ 13 ・ 14
What if?
In our previous lesson we talked a lot about conditional statements. Now we’re about to put it to turbo-drive. Introducing the if statement.
The great thing about if statements is that they only execute the code if the given expression is true. This is very powerful, and has endless applications.
Let me show you an example!
if (2 > 1)
{
Console.WriteLine("Worked!");
}
The above code will execute the code wrapped around the curly braces {} since 2 >1 is true. But if say, 2 < 1, the console will not display the string “Worked!” because 2<1 is false. This is generally the syntax for an if statement in C#.
Of course, when we use fixed numbers like that, the statement will never change. But if statements shine when variables are used. Let me show you.
int airplanes_in_hanger = 0;if (airplanes_in_hanger > 3)
{
Console.WriteLine("Hanger is full!");
}
In here, only when the integer reaches greater than 3, will the console print “Hanger is full”. I hope this is starting to make sense!
Next is else statements. It compliments the if statement, and it only executes its curly braced code given that the if expression is false. Let’s have a look.
int airplanes_in_hanger = 0;if (airplanes_in_hanger > 3)
{
Console.WriteLine("Hanger is full!");
}
else
{
Console.WriteLine("There's still space in the hanger!");
}
In here, it is saying print “Hanger is full!” to the console if the integer variable airplanes_in_hanger is > 3, otherwise print “There’s still space in the hanger!” if that is not true.
As you can notice, else does not depend on an expression. But if you would like it to be bound by an expression, you can use the else if statement.
int airplanes_in_hanger = 0;if (airplanes_in_hanger > 3)
{
Console.WriteLine("Hanger is full!");
}
else if (airplanes_in_hanger > 2 && airplanes_in_hanger < 3)
{
Console.WriteLine("Hanger nearing full capacity!");
}
We used the else if statement bound by 2 expressions using the AND operator. What we are saying with the above code is, print “Hanger is full!” to the console if the integer variable airplanes_in_hanger is > 3, otherwise if the airplanes_in_hanger variable is more than 2 and less than 3, print “Hanger nearing full capacity!”.
Pretty cool right? Now we are beginning to look like programmers! I hope you can see the sheer potential that if, else, and else if statements can have in building solutions to real world problems.
I want you to now write your own program using everything you know from lesson 1 to 5. You can make it about almost anything. Post your code in the comments below!