7.2: If Statements
In this module we'll study if
, else if
, and else
statements.
File Location
Right click on the solution you made in the first module.
Go to Add > New Project and select Console App (.NET Framework).
Name it
07_conditionals_if_else
.Write your code for this module within
Program.cs
of that project.
If, Else If, and Else Statements
In the previous module on booleans, we got a brief introduction to some if
statements. if
statements check to see if a condition is true or false. We also gave a challenge in that module that would require you to use the else
& if else
keywords. Let's add some code that will allow us to write else if
statements:
class Program
{
static void Main(string[] args)
{
//1
Console.WriteLine("How are you feeling today from 1-5?");
string feelingNumber = Console.ReadLine();
//2
if (feelingNumber == "5")
{
Console.WriteLine("That's great to hear!");
}
//3
else if (feelingNumber == "4")
{
Console.WriteLine("Good stuff!");
}
else if (feelingNumber == "3")
{
Console.WriteLine("Hope things get better!");
}
else if (feelingNumber == "2")
{
Console.WriteLine("Oh. Sorry to hear that.");
}
else if (feelingNumber == "1")
{
Console.WriteLine("Dang. We hope your day gets better!");
}
//4
else
{
Console.WriteLine("Sorry, we don't understand. Come back later.");
}
Console.ReadLine();
}
}
Analysis
Here we set up a question in the console that asks a user to enter a value. We store that value in an integer variable.
We check if the number is 5. If it is we will execute another console statement. If the number is not 5 and the expression resolves to false, the program will continue to the
else if
statement.else if
statements are run if the previousif
statements are false. You can have as manyelse if
statements as you want.The
else
statement goes at the end. Similar to thedefault
in a switch,else
statements are run if all previous statements are false.
Multiple if statements
If you have multiple if
statements within a branch, your program will check all those if
statements even if a previous one resulted in true. Not a bad thing, but handy to know especially when you get into the speed of your application.
Add the following code in your Program.cs
file. But, before you run it, try to predict what will print and why.
class Program
{
static void Main(string[] args)
{
bool isOn = true;
bool isHot = false;
if (isOn)
{
Console.WriteLine("The light is on, it's bright.");
}
if (isOn == true)
{
Console.WriteLine("The light is on.");
}
if (isOn && isHot)
{
Console.WriteLine("lights on and it's hot");
}
if (isOn || isHot)
{
Console.WriteLine("lights on or it is hot");
}
if (!isHot)
{
Console.WriteLine("it is not hot");
}
}
}
Last updated