Loops can execute a block of code as long as a specified condition is reached. Loops can be handy as they save time reducing errors and making code more readable.
C# While Loop
The while loop loops through a block of code as long as a specified condition is True. This loop starts with the while keyword, it must include a Boolean conditional expression inside brackets that returns either true or false. It executes code block until specified conditional expression returns false.
Syntax
while (condition)
{
// code block to be executed
}
In the example given below, code in loop will run over again and again as long as a variable(i) is less than 10:
int I = 0;
while( i < 10)
{
Console.WriteLine(i);
i++;
}
Note: We must not forget to increase the variable used in the condition, otherwise loop will never end.
Some rules apply to a switch statement in c#
- The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
- We can any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
- The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
- When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
- When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
- Not every case needs to contain a break. If no break appears, then it will raise a compile time error.
- A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.
Example
using System;
public class Program
{
public static void Main()
{
int weekId = 2;
string weekName="";
switch (weekId) {
case 1:
weekName="Sunday";
Console.WriteLine("This is, {0}",weekName);
break;
case 2:
weekName="Monday";
Console.WriteLine("This is, {0}",weekName);
break;
case 3:
weekName="Tuesday";
Console.WriteLine("This is, {0}",weekName);
break;
case 4:
weekName="Wednesday";
Console.WriteLine("This is, {0}",weekName);
break;
case 5:
weekName="Thursday";
Console.WriteLine("This is, {0}",weekName);
break;
case 6:
weekName="Friday";
Console.WriteLine("This is, {0}",weekName);
break;
default:
Console.WriteLine("Saturday");
break;
}
Console.ReadLine();
}
}
output
This is Monday