Monday, January 6, 2014

C# switch-case statement

The switch-case statement is also use for making decision. However, unlike the if-else statement,we can't test conditions like "greater than" or "less than". In a switch-case, we can test the value of a variable and decide what to do if a particular value is stored in the variable.
Example:

switch(variable to test)
{
   case value1:
   statements if value1 stored in the variable;
   break;

   case value2:
   statements if value12 stored in the varible;
   break;

   default:
   statements if none of the values match:
   break;
}

Example:
The use will enter a weekday number (1 to 7) and the program will display the name of the corresponding day:

static void Main(string[]args)
{
   int day:
   Console.WriteLine("Enter a weekday number (1-7)");
   day = int.Parse(Console.ReadLine()); Switch(day)
   {
    case1:Console.WriteLine("Sunday");
       break;
   case2:Console.WriteLine("Monday");
      break;
   case3:Console.WriteLine("Tuesday");
      break;
   case4:Console.WriteLine("Wednesday");   
      break;
   case5:Console.WriteLine("Thursday");   
      break;
   case6:Console.WriteLine("Friday");  
      break;
   case7:Console.WriteLine("Saturday");   
      break;
   }
}

No comments:

Post a Comment