Tutorial 04: Conditional Statements in C#
The purpose conditional statements is to execute a block of code based on certain condition(s). C# offers following selection statements:
- if
- if else
- if else if
- switch
1. if Statement
if statement is simplest selection statement, it requires a boolean expression followed by a statement or set of statements. if boolean expression evaluates to true, it will executes the block otherwise it will do nothing. Its general syntax is given below:
if(boolean expression)
{
//statement(s)
}
For example:
int a = 4;
if (a < 10) {
Console.WriteLine("a is less than 10");
// This will execute if a is less than 10
}
Console.ReadKey();
2. if else Statement
if else statement expects an boolean expression and it is also followed by else block with both block
contains statement or set of statements. If boolean expression evaluates to true it will execute if block
otherwise it will execute else block. Its general syntax is given below:
if(boolean expression)
{
//statement(s)
}
else
{
//statement(s)
}
For example:
int a = 4;
if (a < 10) {
Console.WriteLine("a is less than 10");
// This will execute if a is less than 10
}
else
{
Console.WriteLine("a is greater than 10");
// This will execute if a is greater than 10
}
Console.ReadKey();
3. if else if Statement
if there more than two conditions on basis of which you want to control your program then you can use if else if provided by C#. In this one, each else if block expects a boolean expression and have statement or set of statements to execute. Lastly there is an else block in case there is no matching to all of conditions. Its general syntax is as follow:
if(boolean expression)
{
//statement(s)
}
else if (boolean expression)
{
//statement(s)
}
...
...
...
else
{
//statement(s)
}
4. Switch Statement
In switch statement, we can test a variable against a collection of values. Each value is referred as a case. Its general form is given below:
switch(expression)
{
case 1:
// code block
break;
case 2:
// code block
break;
...
...
...
case n:
// code block
break;
default:
// code block
break;
}
For example:
char grade = 'B';
switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Well done");
break;
case 'C':
Console.WriteLine("Good");
break;
case 'D':
Console.WriteLine("Satisfactory");
break;
case 'F':
Console.WriteLine("You are Fail");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.ReadKey();
In next lesson we will see iterative structures available in C#
No comments:
Post a Comment