C#. The switch statement




The switch statement


Contents


Search other websites:

1. What use of the operator switch in the program?

The statement “switch” provides multidirectional branching in the program. This statement allows select the choice of the several alternative cases of program executing. In the several cases, the “switch” statement can have more efficiency, than using the “if” statement.

 

2. What is the general view of “switch” statement?

The general vies of “switch” statement is following:

switch (expression)
{
   case constant1:
       statements1;
   break;
   case constant2:
       statements2;
   break;

   ...

   case constantN:
       statementsN;
   break;

   ...

   default:
       statements;
   break;
}

where

  • expression – the given expression of integer type, enumeration type or string type;
  • constant1, constant2, … constantN – the constants of the selection. The type of constants must be compatible with the type of expression. The constants must not have the same values;
  • statements1, statements2, …, statementsN, statements – the sequence of statements, that are executed in the case, if the value of constant coincides with the expression.

If any constant doesn’t coincide with expression, then the statements, that follow after “default” word, are executed.

 

3. What means the default section in the switch statement?

Statements, that follow after default word, are executed in that case, when the expression value doesn’t coincide to any constant. Section default is not mandatory.

If the word default is missing in the switch statement and a constant value is not equal the expression value, then no action is taken.

 



4. An example of using the switch statement without using the default section.

The integer n is given, that specifies the number of the day of week from 1 to 7. By specified number n display the name of corresponding day of week.

The code snippet that solves this task using the switch statement:

...
int n;

n = 7;

switch (n)
{
    case 1: label1.Text = "Monday";
    break;
    case 2: label1.Text = "Tuesday";
    break;
    case 3: label1.Text = "Wednesday";
    break;
    case 4: label1.Text = "Thursday ";
    break;
    case 5: label1.Text = "Friday";
    break;
    case 6: label1.Text = "Saturday";
    break;
    case 7: label1.Text = "Sunday";
    break;
}

 

5. An example of using the switch statement using the default section.

Write a code fragment, which determines the number of days of the month using the number n of month. The number of month days is saved in the k variable.

...

int n, k;

...

switch (n)
{
    case 2:
        k = 28;
    break;
    case 4: case 6: case 9: case 11:
       k = 30;
    break;
    default:
       k = 31;
    break;
}

...

 

6. An example of a program that uses a nested switch statement

The switch statement can be nested in another control statement, which can be:

  • if statement;
  • switch statement;
  • for statement;
  • while statement;
  • do..while statement;
  • foreach statement.

The number of nested levels is unlimited. Therefore, the switch statement can be placed at an arbitrary level of nesting.

In the example, the switch statement contains the nested if statement and the nested switch statement.

The program calculates the number of days in a month based on the entered value of the month number and the year. It takes into account the fact that the year can be a leap year.

The text of the program created using the Console Application template is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            // Nested switch statement
            int year; 
            int month; 
            int days; 

            // input year
            Console.Write("Year = ");
            year = Convert.ToInt32(Console.ReadLine());
            Console.Write("Month = ");
            month = Convert.ToInt32(Console.ReadLine());

            // switch statement containing another nested switch statement
            switch (month)
            {
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;
                    break;
                case 2:
                    bool f; // leap year flag

                    // nested if statement
                    if (year % 400 == 0)
                        f = true;
                    else
                        if (year % 100 == 0)
                            f = false;
                        else
                            if (year % 4 == 0)
                                f = true;
                            else
                                f = false;

                    // nested switch statement
                    switch (f)
                    {
                        case true:
                            days = 29;
                            break;
                        default:
                            days = 28;
                            break;
                    }
                    break;                  
                default:
                    days = 31;
                    break;
            }
            Console.WriteLine("Days = {0}", days);
        }
    }
}

The result of the program

Year = 2100
Month = 2
Days = 28

 

7. Using strings in the switch operator. Example

In addition to integer data, character strings can be used in a switch statement.

Example. In the example of the name of the month shows the number of days in that month. It is assumed that there are 28 days in February.

using System;

namespace ConsoleApp12
{
  class Program
  {
    static void Main(string[] args)
    {
      // Использование строк в операторе выбора switch
      string month; // название месяца

      // 1. Ввести название месяца
      month = Console.ReadLine();

      // 2. Вывести количество дней в месяце
      switch (month)
      {
        case "January":
        case "March":
        case "May":
        case "July":
        case "August":
        case "October":
        case "December":
          Console.WriteLine("Number of days = 31");
          break;
        case "February":
          Console.WriteLine("Number of days = 28");
          break;
        case "April":
        case "June":
        case "September":
        case "November":
          Console.WriteLine("Number of days = 30");
          break;
        default:
          Console.WriteLine("Incorrect input");
          break;
      }
    }
 }
}

 


Related topics