C# If...Else - Real-Life Examples
Real-Life Examples
You have now learned if, else, else if, nested if and logical operators.
This chapter uses them in small programs that solve everyday problems.
Each example starts with a variable that holds the input. In a real program, this value would come from the user (see User Input).
Open a Door with a Code
A door opens only if the entered code is the same as the correct code:
Example
int correctCode = 1234;
int enteredCode = 1234;
if (enteredCode == correctCode)
{
Console.WriteLine("Correct code. The door is now open.");
}
else
{
Console.WriteLine("Wrong code. The door stays closed.");
}
Try to change enteredCode to another number, and run the program again.
Positive or Negative Number
Use else if when there are more than two possible answers. A number can be positive, negative or zero:
Example
int number = -5;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
Old Enough to Vote?
In this example, the voting age is 18. The program tells the person if they can vote, or how many years they have to wait:
Example
int age = 16;
int votingAge = 18;
if (age >= votingAge)
{
Console.WriteLine("You are old enough to vote!");
}
else
{
int yearsLeft = votingAge - age;
Console.WriteLine("You can vote in " + yearsLeft + " years.");
}
age is 16, so the else block runs. It calculates 18 - 16 and prints "You can vote in 2 years."
Grade a Test
This example turns a test score (0 to 100) into a grade:
Example
int score = 75;
if (score >= 90)
{
Console.WriteLine("Excellent!");
}
else if (score >= 70)
{
Console.WriteLine("Good job!");
}
else if (score >= 50)
{
Console.WriteLine("You passed.");
}
else
{
Console.WriteLine("You did not pass this time.");
}
The score is 75. It is not 90 or more, but it is 70 or more, so the program prints "Good job!".