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.

  1. using System;

    • Imports the System namespace, which provides core functionalities, including console input/output.
  2. namespace add_two_numbers

    • Defines a namespace called add_two_numbers to group related classes.
  3. class AddTwoNumbers

    • Declares a class named AddTwoNumbers, which contains the program logic.
  4. static void Main(String[] args)

    • The Main method is the entry point of the program.
    • static means it belongs to the class and does not require an instance.
    • void means the method does not return any value.
    • String[] args allows command-line arguments to be passed.
  5. Declaring Variables:

    • int a, b; → Declares two integer variables.
  6. 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().
    • Similarly, the second number is read and stored in b.

  7. Adding the Two Numbers:

    • int sum = a + b;
      • Calculates the sum of a and b and stores it in the variable sum.
  8. 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