Are you taking your first steps into the world of programming? Looking for a practical and fun project to kick off your journey? Building a simple calculator application using C# and the Visual Studio development environment is an ideal starting point. In this detailed guide, we’ll walk you through creating your first app step by step, with a thorough explanation of every part of the code.
C# is a modern, powerful, and versatile programming language developed by Microsoft as a core part of the .NET Framework platform. It features simple syntax and ease of learning compared to other languages, making it a great choice for beginners.
Key advantages of C#:
Now you are ready to start writing the calculator’s code.
We will build an app that supports the four basic arithmetic operations: addition, subtraction, multiplication, and division. We’ll use basic programming concepts such as variables, loops, and conditional statements.
using System;
using System.Text.RegularExpressions; // Required for Regex
namespace CalculatorApp
{
class Program
{
static void Main(string[] args)
{
bool endApp = false;
Console.WriteLine("Welcome to the Console Calculator in C#\r");
Console.WriteLine("----------------------------------------\n");
while (!endApp)
{
// Declare variables and set to empty
string? numInput1 = "";
string? numInput2 = "";
double result = 0;
// Ask the user for the first number
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput1 = Console.ReadLine();
}
// Ask the user for the second number
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput2 = Console.ReadLine();
}
// Ask the user to choose an operator
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string? op = Console.ReadLine();
// Validate operator input
if (op == null || !Regex.IsMatch(op, "^[asmd]$"))
{
Console.WriteLine("Error: Unrecognized input. Please choose 'a', 's', 'm', or 'd'.");
}
else
{
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else
{
Console.WriteLine($"Your result: {result:0.##}\n");
}
}
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
}
}
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing
}
return;
}
}
public class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number"
// Use a switch statement for the math.
switch (op)
{
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
{
result = num1 / num2;
}
break;
}
return result;
}
}
}
string
).double.TryParse()
method that attempts to convert the text input into a number. If it fails (for example, if the user enters letters), it returns false
, allowing us to prompt the user again for valid input. For more on this method, visit the official Microsoft documentation.Calculator
, which is good practice for organizing code.DoOperation
method uses a switch
statement to select the correct operation based on the user input ('a', 's', 'm', 'd'). The switch
statement is more efficient and cleaner than multiple if-else
statements.try-catch
: The code that may cause unexpected errors is wrapped inside a try
block. If any exception occurs, it is caught in the catch
block and a message is displayed instead of crashing the program.while
loop to allow the user to perform multiple calculations without restarting the program each time.This project is just the beginning. Now you can consider adding more features to improve your app and expand your knowledge:
DoOperation
method to support more complex operations like exponentiation (^
) or square root (sqrt
).You have successfully built your first calculator application using C#. Through this project, you learned the basics of handling user input, validating it, implementing program logic, and handling errors. This project gives you a solid foundation to move on to more complex and challenging projects in software development. Keep experimenting and learning!