Write A C# Program To Add Two Numbers | Write A C# Program To Print The Sum Of Two Numbers

This C# tutorial explains two examples: “Write a c# program to add two numbers” and “Write a c# program to print the sum of two numbers.”

To write a C# program to add two numbers, start by declaring variables for storing the numbers and their sum. Use Console.ReadLine() to take user input, convert it to integers using Convert.ToInt32(), and then add these numbers. Finally, display the sum using Console.WriteLine().

C# program to add two numbers

Let’s learn how to write a simple C# program that adds two numbers. Here’s the complete code to write a c# program to print the sum of two numbers.

using System;

namespace AddTwoNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare variables to store numbers
            int number1, number2, sum;

            // Ask the user to enter the first number
            Console.Write("Enter the first number: ");
            number1 = Convert.ToInt32(Console.ReadLine());

            // Ask the user to enter the second number
            Console.Write("Enter the second number: ");
            number2 = Convert.ToInt32(Console.ReadLine());

            // Calculating the sum of two numbers
            sum = number1 + number2;

            // Displaying the result
            Console.WriteLine("The sum of " + number1 + " and " + number2 + " is: " + sum);

            // Wait for the user to close the console
            Console.ReadKey();
        }
    }
}

You can see here once I run the code using Visual Studio in a console application, it asks me to enter two numbers, and then it shows me the sum of the two numbers like in the screenshot below.

write a c# program to add two numbers

To write a C# program that calculates and prints the sum of two numbers, first create a new Console App project in Visual Studio. In the Program.cs file, define three integer variables, read two numbers from the user, calculate their sum, and display the result using Console.WriteLine().

Conclusion

In this C# tutorial, I have explained how to write a C# program to print the sum of two numbers. This helps to write a c# program to add two numbers.

You may also like: