Creating A Calculator

Lesson 9
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

in C#. Here’s an example of a console-based calculator that can add, subtract, multiply, or divide two numbers entered by the user:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Calculator App!");
            Console.WriteLine("Please enter the first number:");
            double num1 = double.Parse(Console.ReadLine());

            Console.WriteLine("Please enter the second number:");
            double num2 = double.Parse(Console.ReadLine());

            Console.WriteLine("Please select an operation (+, -, *, /):");
            string operation = Console.ReadLine();

            double result = 0;

            switch (operation)
            {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    result = num1 - num2;
                    break;
                case "*":
                    result = num1 * num2;
                    break;
                case "/":
                    if (num2 == 0)
                    {
                        Console.WriteLine("Error: Division by zero!");
                        return;
                    }
                    result = num1 / num2;
                    break;
                default:
                    Console.WriteLine("Error: Invalid operation!");
                    return;
            }

            Console.WriteLine("The result is: " + result);

            Console.ReadKey();
        }
    }
}

In this example, we’re using Console.ReadLine() to get two numbers and an operation entered by the user. We’re then using a switch statement to perform the appropriate operation and store the result in a variable called result. We’re also handling the case where the user attempts to divide by zero or enters an invalid operation.

Note that we’re using double.Parse() to convert the user’s input from a string to a double, so the program will throw an exception if the user enters something that can’t be converted to a number. You can add more input validation to handle this case if necessary.

Also, note that we’re using Console.ReadKey() at the end to prevent the console from closing immediately, allowing the user to see the output of the program.