Building a Calculator Console Application
Intermediate
25 min read
Lesson 3 of 4
Project Overview
We'll build a fully functional calculator with the following features:
- Addition, Subtraction, Multiplication, Division
- Error handling (division by zero, invalid input)
- Continue or exit options
- Clean and user-friendly interface
Step 1: Create the Project Structure
Calculator/
├── Program.cs
├── Calculator.cs
└── Calculator.csproj
Step 2: The Calculator Class
Create a separate class to handle calculations:
using System;
public class Calculator
{
public double Add(double a, double b) => a + b;
public double Subtract(double a, double b) => a - b;
public double Multiply(double a, double b) => a * b;
public double Divide(double a, double b)
{
if (b == 0)
throw new DivideByZeroException("Cannot divide by zero!");
return a / b;
}
}
Step 3: The Main Program
using System;
class Program
{
static void Main()
{
Console.Title = "Calculator App";
Calculator calculator = new Calculator();
while (true)
{
Console.Clear();
Console.WriteLine("=== CALCULATOR ===\n");
// Display menu
Console.WriteLine("Select operation:");
Console.WriteLine("1. Addition (+)");
Console.WriteLine("2. Subtraction (-)");
Console.WriteLine("3. Multiplication (*)");
Console.WriteLine("4. Division (/)");
Console.WriteLine("5. Exit");
Console.Write("\nEnter your choice: ");
string choice = Console.ReadLine();
if (choice == "5")
{
Console.WriteLine("\nGoodbye!");
break;
}
// Get numbers
double num1 = GetNumber("Enter first number: ");
double num2 = GetNumber("Enter second number: ");
// Perform calculation
try
{
double result = 0;
string operation = "";
switch (choice)
{
case "1":
result = calculator.Add(num1, num2);
operation = "+";
break;
case "2":
result = calculator.Subtract(num1, num2);
operation = "-";
break;
case "3":
result = calculator.Multiply(num1, num2);
operation = "*";
break;
case "4":
result = calculator.Divide(num1, num2);
operation = "/";
break;
default:
Console.WriteLine("Invalid choice!");
continue;
}
Console.WriteLine($"\nResult: {num1} {operation} {num2} = {result:F2}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"\nError: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"\nError: {ex.Message}");
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
static double GetNumber(string prompt)
{
while (true)
{
Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out double number))
return number;
Console.WriteLine("Invalid input! Please enter a number.");
}
}
}
Step 4: Enhanced Features
Add History Feature
List history = new List();
// After each calculation
string historyEntry = $"{num1} {operation} {num2} = {result:F2}";
history.Add(historyEntry);
// Display history option
Console.WriteLine("\nPress 'H' to view history");
if (Console.ReadKey().Key == ConsoleKey.H)
{
Console.Clear();
Console.WriteLine("=== HISTORY ===\n");
if (history.Count == 0)
Console.WriteLine("No calculations yet.");
else
{
for (int i = 0; i < history.Count; i++)
Console.WriteLine($"{i + 1}. {history[i]}");
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
Add Scientific Functions
public double Power(double a, double b) => Math.Pow(a, b);
public double SquareRoot(double a) => Math.Sqrt(a);
public double Sine(double a) => Math.Sin(a * Math.PI / 180);
Best Practices
- Separate business logic from UI
- Use exception handling for errors
- Validate user input
- Keep methods focused and single-purpose
Key Takeaway
This project demonstrates key concepts: class design, user input handling, exception handling, and application flow control.
Challenge
Extend the calculator with:
- Percentage calculation
- Memory functions (M+, M-, MR, MC)
- Keyboard shortcuts for operations
- Export history to a text file