If statement in C#
In C#, there are several decision-making statements that you can use to control the flow of your program based on different conditions. The commonly used decision-making statements in C# are:
•If statement
•If-else
•If-else-if
•Switch statement
1. if statement:
In C#, 'if statement' It executes a block of code if a specified condition is true..
Here's the basic syntax of the "if" statement in C#:
if (condition)
{
// Code to be executed if the condition is true
}
If the condition is true, the code block within the curly braces following the "if" statement will be executed. If the condition is false, the code block will be skipped.
Example 'if condition': Checking if a number is positive or negative
int number = 5;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
In this above example value of 'number' variable which greater than 0, the message "The number is positive." is printed.
2. if-else statement:
In C#, the "if-else" statement is used when you want to execute different blocks of code based on the outcome of a condition. If the condition in the "if" statement is true, the code block following the "if" statement is executed. If the condition is false, the code block following the "else" statement is executed instead.
Here's the basic syntax of the "if-else" statement in C#:
if (condition)
{
// Code to be executed if the condition is true
}
else
{
// Code to be executed if the condition is false
}
Here's an example to illustrate the usage of the "if-else" statement:
int number = 10;
if (number % 2 == 0)
{
Console.WriteLine("The number is even.");
}
else
{
Console.WriteLine("The number is odd.");
}
In this example, the condition number % 2 == 0 checks whether the number is divisible by 2 without any remainder. If the condition is true, the message "The number is even." is printed. Otherwise, if the condition is false, the message "The number is odd." is printed.
3. if-else if-else statement (if-else if ladder):
It allows you to test multiple conditions and execute different blocks of code based on the first condition that evaluates to true.
Here's an example of an if-else if statement in C#:
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}
In this example, the code checks the value of the "score" variable and prints out the corresponding grade based on the score range. The if-else if ladder evaluates each condition in order, starting from the top. If a condition is true, the corresponding code block is executed, and the remaining conditions are skipped.
Output:
Grade: B
In this case, since the score is 85, it falls into the second condition (score >= 80). Therefore, the output is "Grade: B".