Introduction:

In this article we will learn how to use switch statement allows you to choose from many statements based on multiple selections by passing control to one of the case statements within its body.

Description:

Switch case is also controlling the flow of program execution in C# programming that evaluates the condition as if else but only difference is that it makes program simpler and easier. It is used when there is multiple if condition in a program. It also includes a default value in Default statements. If no any case matches then Default statements executes and run the code. It Must include break statement in each case and default statements.

Examples of Switch Case

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int opt, value1, value2;
            float result;
        label:
            Console.WriteLine("\n\tMenu");
            Console.WriteLine("\nPress 1 for add");
            Console.WriteLine("Press 2 for subtraction");
            Console.WriteLine("Press 3 for multiplication");
                        Console.WriteLine("Press 4 for Division");
 
            Console.Write("\n\nEnterfirst number:\t");
            value1 = Convert.ToInt32(Console.ReadLine());
 
            Console.Write("Enter second number:\t");
            value2 = Convert.ToInt32(Console.ReadLine());
 
            Console.Write("\nEnter your Menu option:\t");
            opt = Convert.ToInt32(Console.ReadLine());
 
            switch (opt)
            {
                case 1:
                    result = value1 + value2;
                    Console.WriteLine("\n{0} + {1} = {2}", value1, value2, result);
                    break;
                case 2:
                    result = value1 - value2;
                    Console.WriteLine("\n{0} - {1} = {2}", value1, value2, result);
                    break;
                case 3:
                    result = value1 * value2;
                    Console.WriteLine("\n{0} x {1} = {2}", value1, value2, result);
                    break;
                case 4:
                    result = (float)(value1 / value2);
                    Console.WriteLine("\n{0} / {1} = {2}", value1, value2, result);
                    break;
                default:
                    Console.WriteLine("Invalid option. Try again");
                    goto label;
            }
            Console.ReadLine();
 
        }
    }
}

OutPut:



i hope it will help to you after reading it.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.