OneBite.Dev - Coding blog in a bite size

Add Two Numbers In C#

Code snippet for how to Add Two Numbers In C# with sample and detail explanation

In this article, we will demonstrate a simple process in C# programming, which is the ability to add two numbers together. This is one of the fundamental calculation functions in any programming language.

Code snippet for Adding Two Numbers

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter the first number: ");
        int number1 = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter the second number: ");
        int number2 = Convert.ToInt32(Console.ReadLine());

        int sum = number1 + number2;

        Console.WriteLine("The sum is: " + sum);
        Console.ReadLine();
    }
}

Code Explanation for Adding Two Numbers

In the given code snippet, we start by importing the System namespace, which gives us access to basic functionality like reading from and writing to the console.

We then declare a class named Program and within it, we declare a static method named Main. The Main method is the entry point for the program.

The first two lines of code inside the Main method use the Console.Write function to display text asking the user to enter two numbers. The Console.ReadLine() function is then used to capture user input. The Convert.ToInt32() function is used to convert this user input from string to an integer so it can be used in the calculation.

Once we have the two numbers, we add them together and store the result in the sum variable.

The next line of code, Console.WriteLine("The sum is: " + sum); prints the result to the console output.

Finally, Console.ReadLine(); is used to prevent the console from closing immediately, allowing the user to see the sum before ending the program.

That is how you add two numbers in C#. As you can see, it is quite straightforward once you know how to take user input and use it in calculations.

c-sharp