Home »
.Net »
C# Programs
Add Two Numbers in C#
C# program to find the addition of two integer numbers: Here, we are writing a C# program that will read two integer numbers and find their sum.
By IncludeHelp Last updated : April 15, 2023
Adding two numbers
Given (input) two integer numbers and we have to find the addition of given number in C#.
Example
Input:
First number: 10
Second number: 20
Output:
Addition of 10 and 20 is = 30
C# program to add two numbers
using System;
class AddTwoNumbers {
static void Main() {
try {
//declare two variables
int a = 0;
int b = 0;
//input numbers
Console.Write("Enter first number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
b = Convert.ToInt32(Console.ReadLine());
//calculating sum
int sum = a + b;
Console.WriteLine("Addition of " + a + " and " + b + " is = " + sum);
} catch (Exception ex) {
Console.WriteLine("Error: " + ex.ToString());
}
}
}
Output
Enter first number: 10
Enter second number: 20
Addition of 10 and 20 is = 30
Adding two numbers using function
Here, we are defining a function that will take two integer arguments and return the sum of the numbers.
C# program to add two numbers using function
using System;
class AddTwoNumbers {
//defining function
static int sumOfTwoNumber(int x, int y) {
return x + y;
}
//main function
static void Main() {
try {
//declare two variables
int a = 0;
int b = 0;
//input numbers
Console.Write("Enter first number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
b = Convert.ToInt32(Console.ReadLine());
//calculating sum by calling the function
int sum = sumOfTwoNumber(a, b);
Console.WriteLine("Addition of " + a + " and " + b + " is = " + sum);
} catch (Exception ex) {
Console.WriteLine("Error: " + ex.ToString());
}
}
}
Output
Enter first number: 10
Enter second number: 20
Addition of 10 and 20 is = 30
C# Basic Programs »