C# How do you find the sum of 2 numbers

  • Post category:C#

When working with numbers in C#, you may often need to find the sum of two numbers. This can be done with the help of the addition operator, which is represented by the “+” symbol.

To find the sum of two numbers in C#, you can use the following code snippet:

int num1 = 10;
int num2 = 5;
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is {2}", num1, num2, sum);

In the above code, we declare two integer variables num1 and num2 and assign them the values 10 and 5 respectively. We then declare another integer variable sum and assign it the value of num1 + num2, which is the sum of the two numbers. Finally, we use the Console.WriteLine method to display the result.

When you run the code, the output will be:

The sum of 10 and 5 is 15

The code is straightforward and self-explanatory. You can modify the values of num1 and num2 to find the sum of any two numbers in C#.

Alternatively, you can also find the sum of two numbers using user input. Here’s an example:

Console.WriteLine("Enter the first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is {2}", num1, num2, sum);

In the above code, we prompt the user to enter two numbers. We then use the Convert.ToInt32 method to convert the user input from string to an integer. We calculate the sum of the two numbers and display the result using Console.WriteLine.

Remember to add appropriate error handling when dealing with user input, such as checking if the input is a valid number.

Finding the sum of two numbers is a basic operation in C# programming. It is important to understand how to perform this operation as it forms the foundation for more complex calculations and algorithms. Practice different scenarios and experiment with different numbers to gain a better understanding of addition in C#.