C# Add Two Numbers
Learn basic arithmetic operations in C#
➕ Adding Numbers in C#
C# makes arithmetic simple and intuitive. Adding two numbers is a fundamental operation that uses the plus (+) operator to combine numeric values and store results in variables.
// Simple addition example
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
Console.WriteLine("Sum: " + sum);
Output:
Sum: 30
Understanding Addition in C#
Addition is one of the most basic operations in programming. In C#, you can add integers, decimals, and floating-point numbers. The addition operator (+) works with various numeric data types, and C# automatically handles type conversions when needed for compatible types.
Integer Addition
Adding whole numbers
int a = 5;
int b = 3;
int result = a + b;
// result = 8
Decimal Addition
Adding decimal numbers
decimal price1 = 19.99m;
decimal price2 = 5.50m;
decimal total = price1 + price2;
// total = 25.49
Double Addition
Adding floating-point numbers
double x = 10.5;
double y = 20.3;
double sum = x + y;
// sum = 30.8
User Input
Adding user-entered numbers
string input = Console.ReadLine();
int num = int.Parse(input);
int result = num + 10;
🔹 Basic Addition Program
A basic addition program in Python demonstrates fundamental input, processing, and output operations. It typically prompts the user to enter two numbers (converting input from strings to integers or floats), calculates their sum using the + operator, and then prints the result in a user-friendly format. This simple program introduces key concepts like variables, data type conversion, and arithmetic operations. It can be extended with validation using a while loop to ensure the user enters valid numerical input before proceeding.
using System;
class Program
{
static void Main()
{
// Declare and initialize variables
int firstNumber = 15;
int secondNumber = 25;
// Add the numbers
int sum = firstNumber + secondNumber;
// Display the result
Console.WriteLine("First Number: " + firstNumber);
Console.WriteLine("Second Number: " + secondNumber);
Console.WriteLine("Sum: " + sum);
}
}
Output:
First Number: 15 Second Number: 25 Sum: 40
🔹 Adding Numbers from User Input
Adding numbers from user input in C# involves reading data entered by the user and converting it to numeric types for calculation. You can use Console.ReadLine() to capture input as a string, then parse it to an integer or double using methods like int.Parse() or Convert.ToInt32(). Always implement error handling with try-catch blocks or int.TryParse() to manage invalid entries gracefully. This approach ensures robust applications that handle unexpected input without crashing.
using System;
class Program
{
static void Main()
{
// Get first number from user
Console.Write("Enter first number: ");
int num1 = int.Parse(Console.ReadLine());
// Get second number from user
Console.Write("Enter second number: ");
int num2 = int.Parse(Console.ReadLine());
// Calculate sum
int sum = num1 + num2;
// Display result
Console.WriteLine($"The sum of {num1} and {num2} is: {sum}");
}
}
Output:
Enter first number: 12 Enter second number: 8 The sum of 12 and 8 is: 20
🔹 Adding Multiple Numbers
In C#, you can sum multiple numbers efficiently in a single expression or by iterating through a collection. Use the addition operator (+) directly for a fixed set of values, or leverage collections like arrays or lists for dynamic summation. For example, List<int> numbers = new List<int>() { 5, 10, 15 }; can be summed using a foreach loop or LINQ’s Sum() method. This flexibility allows handling both predefined and variable-length sets of numbers seamlessly.
using System;
class Program
{
static void Main()
{
int a = 10;
int b = 20;
int c = 30;
int d = 40;
// Add multiple numbers
int total = a + b + c + d;
Console.WriteLine($"Total: {total}");
// Using an array
int[] numbers = { 5, 10, 15, 20, 25 };
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
Console.WriteLine($"Array Sum: {sum}");
}
}
Output:
Total: 100 Array Sum: 75
🔹 Addition with Different Data Types
Performing addition with different numeric data types in C# requires understanding type conversion and potential precision loss. When adding integers, decimals, floats, or doubles, implicit or explicit casting may be needed. For instance, adding an int and a double results in a double. Use Convert methods or casting like (double)intValue to ensure accuracy. Be mindful of overflow and rounding errors, especially with floating-point arithmetic.
using System;
class Program
{
static void Main()
{
// Integer addition
int intSum = 100 + 50;
Console.WriteLine($"Integer Sum: {intSum}");
// Double addition
double doubleSum = 10.5 + 20.3;
Console.WriteLine($"Double Sum: {doubleSum}");
// Decimal addition (for money)
decimal price1 = 99.99m;
decimal price2 = 49.99m;
decimal totalPrice = price1 + price2;
Console.WriteLine($"Total Price: ${totalPrice}");
// Mixed types (automatic conversion)
double result = 10 + 5.5;
Console.WriteLine($"Mixed Result: {result}");
}
}
Output:
Integer Sum: 150 Double Sum: 30.8 Total Price: $149.98 Mixed Result: 15.5