C# Program to add two numbers
Program
using System;
namespace add_two_numbers
{
class AddTwoNumbers
{
static void Main(String[] args)
{
int a, b;
Console.Write("Enter first number:\t");
a = int.Parse(Console.ReadLine());
Console.Write("Enter second number:\t");
b = int.Parse(Console.ReadLine());
int sum = a + b;
Console.WriteLine("Sum of two numbers: " + sum);
}
}
}
This C# program takes two integer inputs from the user, adds them, and prints the sum.
-
using System;- Imports the
Systemnamespace, which provides core functionalities, including console input/output.
- Imports the
-
namespace add_two_numbers- Defines a namespace called
add_two_numbersto group related classes.
- Defines a namespace called
-
class AddTwoNumbers- Declares a class named
AddTwoNumbers, which contains the program logic.
- Declares a class named
-
static void Main(String[] args)- The
Mainmethod is the entry point of the program. staticmeans it belongs to the class and does not require an instance.voidmeans the method does not return any value.String[] argsallows command-line arguments to be passed.
- The
-
Declaring Variables:
int a, b;→ Declares two integer variables.
-
Reading User Input:
-
Console.Write("Enter first number:\t");- Displays a message asking for input.
-
a = int.Parse(Console.ReadLine());- Reads user input as a string and converts it to an integer using
int.Parse().
- Reads user input as a string and converts it to an integer using
-
Similarly, the second number is read and stored in
b.
-
-
Adding the Two Numbers:
int sum = a + b;- Calculates the sum of
aandband stores it in the variablesum.
- Calculates the sum of
-
Displaying the Result:
Console.WriteLine("Sum of two numbers: " + sum);- Prints the sum to the console.
Output
$ mcs AddTwoNumbers.cs
$ mono AddTwoNumbers.exe
Enter first number: 34
Enter second number: 567
Sum of two numbers: 601