0
0
CsharpProgramBeginner · 2 min read

C# Program to Create Simple Calculator

A simple C# calculator program reads two numbers and an operator from the user, then uses switch to perform addition, subtraction, multiplication, or division, and prints the result.
📋

Examples

Input5, 3, +
OutputResult: 8
Input10, 2, /
OutputResult: 5
Input7, 0, /
OutputCannot divide by zero.
🧠

How to Think About It

To create a simple calculator, first get two numbers and an operator from the user. Then, decide which operation to perform based on the operator using switch. Finally, calculate and show the result, handling special cases like division by zero.
📐

Algorithm

1
Get the first number from the user.
2
Get the second number from the user.
3
Get the operator (+, -, *, /) from the user.
4
Use a switch to check the operator and perform the matching operation.
5
If division is chosen, check if the second number is zero to avoid errors.
6
Print the result or an error message.
💻

Code

csharp
using System;
class Calculator {
    static void Main() {
        Console.Write("Enter first number: ");
        double num1 = double.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        double num2 = double.Parse(Console.ReadLine());
        Console.Write("Enter operator (+, -, *, /): ");
        char op = Console.ReadLine()[0];

        double result = 0;
        bool valid = true;

        switch (op) {
            case '+': result = num1 + num2; break;
            case '-': result = num1 - num2; break;
            case '*': result = num1 * num2; break;
            case '/':
                if (num2 != 0) result = num1 / num2;
                else {
                    Console.WriteLine("Cannot divide by zero.");
                    valid = false;
                }
                break;
            default:
                Console.WriteLine("Invalid operator.");
                valid = false;
                break;
        }

        if (valid) Console.WriteLine($"Result: {result}");
    }
}
Output
Enter first number: 5 Enter second number: 3 Enter operator (+, -, *, /): + Result: 8
🔍

Dry Run

Let's trace the input 5, 3, + through the code

1

Read first number

num1 = 5

2

Read second number

num2 = 3

3

Read operator

op = '+'

4

Switch on operator

case '+': result = 5 + 3 = 8

5

Print result

Output: Result: 8

StepVariableValue
1num15
2num23
3op+
4result8
💡

Why This Works

Step 1: Input reading

The program reads two numbers and an operator from the user using Console.ReadLine() and converts the numbers to double.

Step 2: Operation selection

It uses a switch statement on the operator to decide which arithmetic operation to perform.

Step 3: Division check

Before dividing, it checks if the second number is zero to avoid a runtime error and prints a message if division is not possible.

Step 4: Output result

If the operation is valid, it prints the result using string interpolation with $"Result: {result}".

🔄

Alternative Approaches

Using if-else instead of switch
csharp
using System;
class Calculator {
    static void Main() {
        Console.Write("Enter first number: ");
        double num1 = double.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        double num2 = double.Parse(Console.ReadLine());
        Console.Write("Enter operator (+, -, *, /): ");
        char op = Console.ReadLine()[0];

        double result = 0;
        bool valid = true;

        if (op == '+') result = num1 + num2;
        else if (op == '-') result = num1 - num2;
        else if (op == '*') result = num1 * num2;
        else if (op == '/') {
            if (num2 != 0) result = num1 / num2;
            else {
                Console.WriteLine("Cannot divide by zero.");
                valid = false;
            }
        } else {
            Console.WriteLine("Invalid operator.");
            valid = false;
        }

        if (valid) Console.WriteLine($"Result: {result}");
    }
}
This approach is straightforward but can be longer and less clear than switch for multiple cases.
Using a method to perform calculation
csharp
using System;
class Calculator {
    static double Calculate(double a, double b, char op) {
        return op switch {
            '+' => a + b,
            '-' => a - b,
            '*' => a * b,
            '/' => b != 0 ? a / b : throw new DivideByZeroException(),
            _ => throw new ArgumentException("Invalid operator")
        };
    }

    static void Main() {
        Console.Write("Enter first number: ");
        double num1 = double.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        double num2 = double.Parse(Console.ReadLine());
        Console.Write("Enter operator (+, -, *, /): ");
        char op = Console.ReadLine()[0];

        try {
            double result = Calculate(num1, num2, op);
            Console.WriteLine($"Result: {result}");
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}
This uses modern C# switch expressions and exception handling for cleaner separation of logic.

Complexity: O(1) time, O(1) space

Time Complexity

The program performs a fixed number of operations regardless of input size, so it runs in constant time O(1).

Space Complexity

It uses a fixed amount of memory for variables and no extra data structures, so space complexity is O(1).

Which Approach is Fastest?

All approaches run in constant time; using a switch or if-else has negligible difference. Using a method with exceptions adds slight overhead but improves code clarity.

ApproachTimeSpaceBest For
Switch statementO(1)O(1)Simple and clear multiple operations
If-else statementsO(1)O(1)Simple logic, fewer cases
Method with switch expressionO(1)O(1)Clean code and error handling
💡
Always check for division by zero to avoid runtime errors in your calculator.
⚠️
Beginners often forget to handle invalid operators or division by zero, causing crashes.