Subtraction of two numbers in C++

By | February 20, 2024

In this article, we have discussed various methods to subtract two numbers in C++. These are simple program, you can learn them easily.

Method-1 : With Hardcoded Inputs


#include <iostream>
using namespace std;
 
// driver
int main() {
 
   // first number is 5
   int x = 5;
 
   // second number is 6
   int y = 6;
 
   // resultant number
   int subtract = x - y;
   cout <<  subtract;
   return 0;
}

Output:

-1 

Method-2 : With user Inputs

#include <iostream>
using namespace std;
 
// driver
int main() {
 
   // for inputs
   int x, y;
 
   // for output
   int  subtract;
 
   cout << "first number: ";
   cin >> x;
   cout << "second number: ";
   cin >> y;
    
    // subtraction of both numbers
    subtract = x - y;
   cout << " subtract is: " <<  subtract;
   return 0;
}

Output:
Output depends on user inputs, that will be subtraction of both numbers.

Method-3 : With class

#include <iostream>
using namespace std;

class Subtract {
    // for inputs
    int x, y;

public:
    // input numbers
    void input() {
        cout << "Input two integers\n";
        cin >> x >> y;
    }
    
    // perform subtraction
    void performSubtraction() {
        // subtraction of both numbers
        cout << "Result: " << x - y;
    }
};

// driver
int main() {
    // object of class
    Subtract m;

    m.input();
    m.performSubtraction();

    return 0;
}

Output:
Output depends on user inputs, that will be subtraction of both numbers.

Method-4 : With array elements

#include <iostream>
using namespace std;
 
//driver
int main() {
 
   // create array
   int a[3];
 
   // initialize array 
   a[0]=15;
   a[1]=10;
 
   //  subtraction of first two elements
   a[2]=a[0] - a[1];
   cout<<" subtraction of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
   return 0;
}

Output:

Subtraction of 15 and 10 is 5 

You can watch this good video about this topic:



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.