The else if statement in C# is a conditional statement that allows you to check multiple conditions in sequence. It follows an initial if block and is used when you need to evaluate additional conditions after the first condition fails. Each else if block provides an alternative condition to test.
Syntax:
if (condition1)
{
// Executes if condition1 is true
}
else if (condition2)
{
// Executes if condition2 is true and condition1 is false
}
else
{
// Executes if none of the above conditions are true
}
Explanation:
- if: Evaluates the first condition.
- else if: Provides additional conditions to check if the previous if or else if conditions were false.
- else: A fallback option if none of the previous conditions are true.
Example:
using System;
public class MyData
{
public static void Main(string[] args)
{
int number = 25;
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.");
}
}
}
Output:
The number is positive.
If we pass number= -25 in the above code then Output will be
The number is negative.
If we pass number= 0 in the above code then Output will be
The number is zero.