Calculator - switch Learn programming C#

Lesson:

Basic Data Types


Exercise:

Calculator - switch


Objetive:

Write a C# program that asks the user for two numbers and an operation to perform on them (+,-,*,x,/) and displays the result of that operation, as in this example:

Enter the first number: 5
Enter the operation: +
Enter the second number: 7
5+7=12

Note: You MUST use 'switch', not 'if'.


Code:

using System;
public class exercise054
{
    public static void Main()
    {
        int a, b;
        char operation;

        Console.Write("Enter first number: ");
        a = Convert.ToInt32(Console.ReadLine());
        Console.Write("Enter operation: ");
        operation = Convert.ToChar(Console.ReadLine());
        Console.Write("Enter second number: ");
        b = Convert.ToInt32(Console.ReadLine());

        switch (operation)
        {
            case '+':
                Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
                break;
            case '-':
                Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
                break;
            case 'x':
            case '*':
                Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
                break;
            case '/':
                Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
                break;
            default:
                Console.WriteLine("Wrong Character");
                break;
        }
    }
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.