Using if Statements in C#
When we want to choose between executing two different blocks of code depending on the result of a Boolean expression, we can use an if statement.
Syntax:-
The syntax of an if statement is as follows (if and else are C# keywords):
if ( booleanExpression )
statement-1;
else
statement-2;
If booleanExpression evaluates to true, statement-1 runs; otherwise, statement-2 runs. The else keyword and the subsequent statement-2 are optional. If there is no else clause and the booleanExpression is false, execution continues with whatever code follows the if statement. For example, here’s an if statement that increments a variable representing the second hand
of a stopwatch (Minutes are ignored for now). If the value of the seconds variable is 59, it is reset to 0; otherwise, it is incremented using the ++ operator:
int seconds;
...
if (seconds == 59)
seconds = 0;
else
seconds++;
Grouping Statements:-
Notice that the syntax of the if statement shown earlier specifes a single statement after the if (booleanExpression) and a single statement after the else keyword. Sometimes, we want to perform more than one statement when a Boolean expression is true. We can group the statements inside a new method and then call the new method, but a simpler solution is to group the statements inside a block. A block is simply a sequence of statements grouped between an opening brace and a closing brace. A block also starts a new scope. We can defne variables inside a block, but they will disappear at the end of the block.
In the following example, two statements that reset the seconds variable to 0 and increment the minutes variable are grouped inside a block, and the whole block executes if the value of seconds is equal to 59:
int seconds = 0;
int minutes = 0;
...
if (seconds == 59)
{
seconds = 0;
minutes++;
}
else
seconds++;
Nested if Statements:-
We can nest if statements inside other if statements. In this way, we can chain together a sequence of Boolean expressions, which are tested one after the other until one of them evaluates to true. In the following example, if the value of day is 0, the frst test evaluates to true and dayName is assigned the string “Sunday”. If the value of day is not 0, the frst test fails and control passes to the else clause, which runs the second if statement and compares the value of day with 1. The second if statement is reached only if the frst test is false. Similarly, the third if statement is reached only if the frst and second tests are false.
if (day == 0)
dayName = "Sunday";
else if (day == 1)
dayName = "Monday";
else if (day == 2)
dayName = "Tuesday";
else if (day == 3)
dayName = "Wednesday";
else if (day == 4)
dayName = "Thursday";
else if (day == 5)
dayName = "Friday";
else if (day == 6)
dayName = "Saturday";
else
dayName = "unknown";
Comments
Post a Comment