C# Program to subtract two numbers

Program

using System;
namespace subtract_two_numbers
{
	class SubtractTwoNumbers
	{
		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 sub = a - b;
			Console.WriteLine("Difference of two numbers: " + sub);
		}
	}
}

This C# program takes two integer inputs from the user, subtracts the second number from the first, and prints the result.

  1. using System;

    • Imports the System namespace, which provides built-in functionalities like console input and output.
  2. namespace subtract_two_numbers

    • Defines a namespace named subtract_two_numbers to organize related classes.
  3. class SubtractTwoNumbers

    • Declares a class named SubtractTwoNumbers, which contains the main logic of the program.
  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 passing command-line arguments.
  5. Declaring Variables:

    • int a, b; → Declares two integer variables to store user input.
  6. Reading User Input:

    • Console.Write("Enter first number:\t");

      • Prompts the user to enter the first number.
    • a = int.Parse(Console.ReadLine());

      • Reads the input as a string and converts it to an integer using int.Parse().
    • Similarly, the second number is read and stored in b.

  7. Subtracting the Two Numbers:

    • int sub = a - b;
      • Computes the difference between a and b and stores it in sub.
  8. Displaying the Result:

    • Console.WriteLine("Difference of two numbers: " + sub);
      • Prints the subtraction result to the console.

Output

$ mcs SubtractTwoNumbers.cs 
$ mono SubtractTwoNumbers.exe 
Enter first number:	456
Enter second number:	23
Difference of two numbers: 433