Curriculum
The if-else statement is a conditional statement in C# that allows you to execute different code blocks based on whether a condition is true or false. The basic syntax of an if-else statement in C# is as follows:
if (condition)
{
// code to execute if condition is true
}
else
{
// code to execute if condition is false
}
Here, condition is a Boolean expression that evaluates to true or false. If condition is true, the code block inside the first set of curly braces is executed. If condition is false, the code block inside the second set of curly braces is executed.
Here is an example of using an if-else statement in C#:
int num = 10;
if (num > 0)
{
Console.WriteLine("num is positive");
}
else
{
Console.WriteLine("num is negative or zero");
}
In this example, the if statement checks whether the value of num is greater than 0. If it is, the message “num is positive” is printed to the console. If it is not, the message “num is negative or zero” is printed instead.
You can also use multiple if-else statements to test for more than two conditions. Here is an example:
int score = 85;
if (score >= 90)
{
Console.WriteLine("You got an A!");
}
else if (score >= 80)
{
Console.WriteLine("You got a B!");
}
else if (score >= 70)
{
Console.WriteLine("You got a C!");
}
else
{
Console.WriteLine("You failed.");
}
In this example, the code tests the value of score and prints a message based on the range of values that it falls into. If score is 90 or higher, the message “You got an A!” is printed. If score is between 80 and 89, the message “You got a B!” is printed, and so on. If score is less than 60, the message “You failed.” is printed.
The if-else statement is a powerful tool in C# that allows you to write programs that can make decisions based on input or other factors.