create a calculator in csharp

Here is an example of a simple calculator in C# console application using if-else statements and while loop:

main.cs
using System;

namespace CalculatorProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            double result = 0.0;
            bool validInput = false;

            while (!validInput)
            {
                Console.WriteLine("Enter a basic arithmetic operation (+, -, *, /) or 'q' to quit:");
                string operation = Console.ReadLine();

                if (operation == "+" || operation == "-" || operation == "*" || operation == "/")
                {
                    Console.WriteLine("Enter the first operand:");
                    double num1 = Convert.ToDouble(Console.ReadLine());

                    Console.WriteLine("Enter the second operand:");
                    double num2 = Convert.ToDouble(Console.ReadLine());

                    if (operation == "+")
                    {
                        result = num1 + num2;
                        Console.WriteLine($"The result of {num1} + {num2} is {result}");
                    }
                    else if (operation == "-")
                    {
                        result = num1 - num2;
                        Console.WriteLine($"The result of {num1} - {num2} is {result}");
                    }
                    else if (operation == "*")
                    {
                        result = num1 * num2;
                        Console.WriteLine($"The result of {num1} * {num2} is {result}");
                    }
                    else if (operation == "/")
                    {
                        if (num2 == 0)
                        {
                            Console.WriteLine("Error: Cannot divide by zero");
                        }
                        else
                        {
                            result = num1 / num2;
                            Console.WriteLine($"The result of {num1} / {num2} is {result}");
                        }
                    }
                }
                else if (operation == "q")
                {
                    Console.WriteLine("Quitting calculator program...");
                    validInput = true;
                }
                else
                {
                    Console.WriteLine("Invalid input. Please enter a valid operation.");
                }
            }
        }
    }
}
2336 chars
66 lines

This calculator program prompts the user to enter an arithmetic operation (+, -, *, /) or 'q' to quit. If the input is valid, it prompts the user for two operands and performs the specified operation. If the input is invalid, it displays an error message and prompts the user again. The program continues to run until the user enters 'q' to quit.

gistlibby LogSnag