C# if...else Statement
The if...else
statement in C# allows you to conditionally execute one block of code or another based on a boolean expression.
Here's the basic syntax of an if...else
statement in C#:
if (boolean_expression) { // code to execute if boolean_expression is true } else { // code to execute if boolean_expression is false }
The boolean_expression
is any expression that returns a boolean value (true
or false
). If the boolean_expression
is true
, the code inside the first block will be executed. Otherwise, the code inside the second block will be executed.
Here's an example of using the if...else
statement to determine whether a number is even or odd:
int num = 5; if (num % 2 == 0) { Console.WriteLine(num + " is even"); } else { Console.WriteLine(num + " is odd"); }
In this example, if the remainder of num
divided by 2 is equal to 0, then the if
block will be executed, indicating that num
is even. Otherwise, the else
block will be executed, indicating that num
is odd.
You can also use nested if...else
statements to test multiple conditions. For example:
int score = 75; 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 program tests the value of score
against a series of conditions, printing out the corresponding letter grade based on the score.