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.
-
using System;
- Imports the
System
namespace, which provides built-in functionalities like console input and output.
- Imports the
-
namespace subtract_two_numbers
- Defines a namespace named
subtract_two_numbers
to organize related classes.
- Defines a namespace named
-
class SubtractTwoNumbers
- Declares a class named
SubtractTwoNumbers
, which contains the main logic of the program.
- Declares a class named
-
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.
- The
-
Declaring Variables:
int a, b;
→ Declares two integer variables to store user input.
-
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()
.
- Reads the input as a string and converts it to an integer using
-
Similarly, the second number is read and stored in
b
.
-
-
Subtracting the Two Numbers:
int sub = a - b;
- Computes the difference between
a
andb
and stores it insub
.
- Computes the difference between
-
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