Software & Finance





C# - Switch Case Example for Simple Arithmetic Operations





I have given here a switch case statement example in C#. Switch Case works better where are many if else conditions required. It gives better clarity and easy code maintenance.

 

The following source code will accept the user choice for addition, subtraction, multiplication and division. And then it will accept two numbers as input then uses switch case to perform the computation and print the result.

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace SwitchCase

{

class SwitchCaseExample

   {

      static bool ReadInteger(out int n)

      {

         string input = System.Console.ReadLine();

         n = 0;

         try

         {

            n = Convert.ToInt32(input);

            return true;

         }

         catch (System.Exception ex)

         {

            System.Console.WriteLine("Error in the input format\n\n");

            return false;

         }

      }

 

      static void Main(string[] args)

      {

         int a, b, opcode, result;

         System.Console.WriteLine("Program for Addition, Subtraction, Multiplication and Division\n");

 

         while (true)

         {

            System.Console.Write("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: ");

            ReadInteger(out opcode);

 

            if (opcode < 1 || opcode > 4)

               return;

 

            System.Console.Write("Enter First Number:");

            ReadInteger(out a);

            System.Console.Write("Enter Second Number:");

            ReadInteger(out b);

 

            switch (opcode)

            {

               case 1:

                  result = a + b;

                  System.Console.WriteLine("{0} + {1} = {2}", a, b, result);

                  break;

 

               case 2:

                  result = a - b;

                  System.Console.WriteLine("{0} - {1} = {2}", a, b, result);

                  break;

 

               case 3:

                  result = a * b;

                  System.Console.WriteLine("{0} * {1} = {2}", a, b, result);

                  break;

 

               case 4:

                  result = a / b;

                  System.Console.WriteLine("{0} / {1} = {2}\n{3} % {4} = {5}", a, b, result, a, b, a % b);

                  break;

               default:

                  break;

            }

         }

      }

   }

}

Output