The if-else statement
Explains the if-else statement and how it works in a C# program
Before we write some code using the if-else statement, let us look at the basic syntax of if-else.
if (condition)
{
statements to execute if the condition is true;
}
else
{
statements to execute if the condition is false;
}
Here, `if' and `else' are keywords. We test a condition with `if'. If that condition is true, the statements inside the block just after `if' will execute. If the condition is false, the statements inside the block after `else' will execute.
The following program uses the `if-else' construct to find if the number entered by the user is even or odd:
static void Main(string[] args) { int num;
Console.WriteLine("Enter a number"); num = int.Parse(Console.ReadLine());
if (num % 2 == 0) { Console.WriteLine("The number is even"); } else { Console.WriteLine("The number is odd"); } }
Here, the `if' statement checks if the number is divisible by 2.
if (num % 2 == 0)
If this condition is true, the code inside the `if' block will execute and we will get the message "The number is Even". However, if the condition is not true, the statement inside the else block will execute and the output will be "The number is odd".
We can test multiple conditions using the if-else statement. For this, the syntax is:
if (condition 1)
{
statements if the condition 1 is true;
}
else if (condition 2)
{
statements if the condition 2 is true;
}
else if (condition 3)
{
statements if the condition 3 is true;
}
.
.
.
else
{
statements if none of the conditions are true;
}