Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Basic calculator program using C#
A calculator program in C# can be built using either Windows Forms or Console applications. This tutorial demonstrates how to create a basic calculator that performs fundamental arithmetic operations like addition, subtraction, multiplication, and division.
We'll create a complete console-based calculator that takes user input and performs calculations, making it easy to understand the core logic before moving to GUI implementations.
Console-Based Calculator
Basic Calculator with Menu
using System;
class Calculator {
public static void Main(string[] args) {
double num1, num2, result;
char operation;
Console.WriteLine("=== Basic Calculator ===");
Console.WriteLine("Enter first number: ");
num1 = 10.5; // Simulating user input
Console.WriteLine("10.5");
Console.WriteLine("Enter operation (+, -, *, /): ");
operation = '+'; // Simulating user input
Console.WriteLine("+");
Console.WriteLine("Enter second number: ");
num2 = 5.2; // Simulating user input
Console.WriteLine("5.2");
switch (operation) {
case '+':
result = num1 + num2;
Console.WriteLine($"{num1} + {num2} = {result}");
break;
case '-':
result = num1 - num2;
Console.WriteLine($"{num1} - {num2} = {result}");
break;
case '*':
result = num1 * num2;
Console.WriteLine($"{num1} * {num2} = {result}");
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
Console.WriteLine($"{num1} / {num2} = {result}");
} else {
Console.WriteLine("Error: Division by zero!");
}
break;
default:
Console.WriteLine("Invalid operation!");
break;
}
}
}
The output of the above code is −
=== Basic Calculator === Enter first number: 10.5 Enter operation (+, -, *, /): + Enter second number: 5.2 10.5 + 5.2 = 15.7
Object-Oriented Calculator
Calculator Class with Methods
using System;
class Calculator {
public double Add(double a, double b) {
return a + b;
}
public double Subtract(double a, double b) {
return a - b;
}
public double Multiply(double a, double b) {
return a * b;
}
public double Divide(double a, double b) {
if (b == 0) {
throw new DivideByZeroException("Cannot divide by zero!");
}
return a / b;
}
public double Power(double baseNum, double exponent) {
return Math.Pow(baseNum, exponent);
}
public double SquareRoot(double number) {
if (number < 0) {
throw new ArgumentException("Cannot calculate square root of negative number!");
}
return Math.Sqrt(number);
}
}
class Program {
public static void Main(string[] args) {
Calculator calc = new Calculator();
Console.WriteLine("=== Calculator Operations ===");
Console.WriteLine("Addition: " + calc.Add(15, 25));
Console.WriteLine("Subtraction: " + calc.Subtract(50, 30));
Console.WriteLine("Multiplication: " + calc.Multiply(6, 7));
Console.WriteLine("Division: " + calc.Divide(100, 4));
Console.WriteLine("Power: " + calc.Power(2, 3));
Console.WriteLine("Square Root: " + calc.SquareRoot(64));
// Demonstrating error handling
try {
Console.WriteLine("Division by zero: " + calc.Divide(10, 0));
} catch (DivideByZeroException ex) {
Console.WriteLine("Error: " + ex.Message);
}
}
}
The output of the above code is −
=== Calculator Operations === Addition: 40 Subtraction: 20 Multiplication: 42 Division: 25 Power: 8 Square Root: 8 Error: Cannot divide by zero!
Windows Forms Calculator Structure
For GUI-based calculators using Windows Forms, the basic structure involves button click events. Here's the corrected approach for handling operations −
public partial class Calculator : Form {
private double firstNumber = 0;
private double secondNumber = 0;
private char operation;
private bool operationPressed = false;
private void btnAdd_Click(object sender, EventArgs e) {
firstNumber = Convert.ToDouble(txtResult.Text);
operation = '+';
operationPressed = true;
txtResult.Clear();
}
private void btnEquals_Click(object sender, EventArgs e) {
secondNumber = Convert.ToDouble(txtResult.Text);
double result = 0;
switch (operation) {
case '+': result = firstNumber + secondNumber; break;
case '-': result = firstNumber - secondNumber; break;
case '*': result = firstNumber * secondNumber; break;
case '/':
if (secondNumber != 0)
result = firstNumber / secondNumber;
else {
txtResult.Text = "Error";
return;
}
break;
}
txtResult.Text = result.ToString();
operationPressed = false;
}
}
Advanced Calculator with Multiple Operations
using System;
class AdvancedCalculator {
public static double Calculate(double num1, double num2, string operation) {
switch (operation.ToLower()) {
case "add":
case "+":
return num1 + num2;
case "subtract":
case "-":
return num1 - num2;
case "multiply":
case "*":
return num1 * num2;
case "divide":
case "/":
return num2 != 0 ? num1 / num2 : throw new DivideByZeroException();
case "modulo":
case "%":
return num1 % num2;
default:
throw new ArgumentException("Invalid operation");
}
}
public static void Main(string[] args) {
double a = 20, b = 8;
Console.WriteLine("=== Advanced Calculator ===");
Console.WriteLine($"Numbers: {a}, {b}");
Console.WriteLine();
string[] operations = { "+", "-", "*", "/", "%" };
string[] names = { "Addition", "Subtraction", "Multiplication", "Division", "Modulo" };
for (int i = 0; i < operations.Length; i++) {
try {
double result = Calculate(a, b, operations[i]);
Console.WriteLine($"{names[i]}: {a} {operations[i]} {b} = {result}");
} catch (DivideByZeroException) {
Console.WriteLine($"{names[i]}: Error - Division by zero");
}
}
// Scientific operations
Console.WriteLine($"Power: {a}^3 = {Math.Pow(a, 3)}");
Console.WriteLine($"Square Root: ?{a} = {Math.Sqrt(a):F2}");
Console.WriteLine($"Absolute: |{-a}| = {Math.Abs(-a)}");
}
}
The output of the above code is −
=== Advanced Calculator === Numbers: 20, 8 Addition: 20 + 8 = 28 Subtraction: 20 - 8 = 12 Multiplication: 20 * 8 = 160 Division: 20 / 8 = 2.5 Modulo: 20 % 8 = 4 Power: 20^3 = 8000 Square Root: ?20 = 4.47 Absolute: |-20| = 20
Key Features of Calculator Programs
-
Error Handling: Always check for division by zero and invalid inputs.
-
Data Types: Use
doublefor decimal calculations instead ofint. -
User Interface: Provide clear prompts and formatted output.
-
Validation: Validate user input before performing calculations.
-
Extensibility: Design the calculator to easily add new operations.
Conclusion
Building a calculator program in C# involves understanding basic arithmetic operations, error handling, and user interface design. Whether using console applications or Windows Forms, the core logic remains the same: capture input, perform calculations, and display results with proper error handling for edge cases like division by zero.
