4 Function Calculator

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

Here’s an example of a four-function calculator in C#:

using System;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Calculator program!");
            Console.WriteLine("Please enter an operation (+, -, *, /):");
            string operation = Console.ReadLine();
            Console.WriteLine("Please enter the first number:");
            double num1 = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Please enter the second number:");
            double num2 = Convert.ToDouble(Console.ReadLine());

            double result = 0;

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

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

Let me explain what this code does.

First, we prompt the user to enter an operation, first number, and second number using Console.WriteLine() and Console.ReadLine(). We convert the user inputs for the numbers to double data type using Convert.ToDouble().

Next, we declare a variable result and initialize it to 0. This variable will hold the final result of the calculation.

Then we use an if-else statement to check which operation the user entered. If it’s addition, we add num1 and num2 and store the result in result. If it’s subtraction, we subtract num2 from num1 and store the result in result. If it’s multiplication, we multiply num1 and num2 and store the result in result. If it’s division, we check if num2 is not zero, then we divide num1 by num2 and store the result in result. If num2 is zero, we display an error message using Console.WriteLine() and return from the program using return;. If the user entered an invalid operation, we display an error message and return from the program.

Finally, we display the result to the user using Console.WriteLine().