if-else C# Language
If-else statements are fundamental constructs in programming, allowing you to make decisions and control the flow of your code based on conditions. In
If-else statements are fundamental constructs in programming, allowing you to make decisions and control the flow of your code based on conditions. In
An if-else statement consists of the following components:
if
keyword: It’s used to start the conditional statement.if
block should be executed.else
keyword (optional): If the condition is false, you can provide an alternative code block to execute using the else
statement.Let’s start with a simple example. Suppose you want to check whether a number is even or odd and display a message accordingly:
int number = 6;
if (number % 2 == 0)
{
Console.WriteLine("The number is even.");
}
else
{
Console.WriteLine("The number is odd.");
}
In this code, number % 2 == 0
is the condition. If the condition is true (in this case, if the number is even), the code inside the if
block will execute. If it’s false (the number is odd), the code inside the else
block will execute.
You can also create a chain of conditions using if
, else if
, and else
to handle multiple cases. Let’s say you want to classify a student’s performance based on their exam score:
int score = 85;
if (score >= 90)
{
Console.WriteLine("Excellent");
}
else if (score >= 70)
{
Console.WriteLine("Good");
}
else if (score >= 50)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
In this example, the program checks multiple conditions one by one, and once a true condition is found, the corresponding code block is executed.
You can also nest if-else statements to handle more complex scenarios. Here’s an example of nested if-else statements to determine whether a number is positive, negative, or zero:
int value = -5;
if (value > 0)
{
Console.WriteLine("The number is positive.");
}
else if (value < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
Subscribe to get the latest posts sent to your email.