Your Complete Guide to Building a Calculator Using C# and Visual Studio (for Beginners)

Your Complete Guide to Building a Calculator Using C# and Visual Studio

Your Complete Guide to Building a Calculator Using C# and Visual Studio (for Beginners)

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.

Why C# Is the Perfect Choice for Your First Project

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#:

  • Integrated Development Environment (IDE): Visual Studio provides powerful tools to help write code and debug with ease.
  • Power of the .NET platform: C# gives you access to a massive library of ready-made functions that speed up development.
  • Memory Safety: The language automatically manages memory, reducing common memory-related bugs and making your applications more stable.

Setting Up Your Environment and Creating Your First Project

  1. Open Visual Studio: Launch the program on your device.
  2. Create a new project: From the top menu, select "File" > "New" > "Project."
  3. Choose the right template: In the "Create a new project" window, search for "Console App" and make sure you select the C# version. This template is perfect for command-line applications.
  4. Name your project: Give your project a meaningful name, like "MyCalculatorApp," then click "Create."

Now you are ready to start writing the calculator’s code.

Writing the Code for the Calculator Application

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;
        }
    }
}
        

Detailed Code Explanation 🧐

  • Input Handling: The program starts by asking the user for two numbers and the operation choice. These inputs are stored as text variables (string).
  • Input Validation: This is a crucial step to ensure app stability. We use the 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.
  • Performing Calculations:
    • The calculation logic is separated into a dedicated class named Calculator, which is good practice for organizing code.
    • The 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.
  • Error Handling:
    • Division by zero: Inside the division case, the code checks that the divisor is not zero to avoid a common mathematical error.
    • Using 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.
  • Application Continuity: The app uses a while loop to allow the user to perform multiple calculations without restarting the program each time.

Next Steps: Additional Enhancements for Your Application

This project is just the beginning. Now you can consider adding more features to improve your app and expand your knowledge:

  1. Add new operations: Modify the DoOperation method to support more complex operations like exponentiation (^) or square root (sqrt).
  2. Build a graphical user interface (GUI): Move from a console app to a real desktop application. Explore technologies like Windows Forms or WPF (Windows Presentation Foundation), which is the latest and more powerful technology for building rich user interfaces on the .NET platform.

Conclusion

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!

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
-->