Division of two numbers in C++

By | February 20, 2024

In this article, we have discussed various methods to divide 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 4
   int x = 4;
  
   // second number is 2
   int y = 2;
  
   // resultant number
   int division = x / y;
   cout <<  division;
   return 0;
}

Output:

2 

Method-2 : With user Inputs

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

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

Method-3 : With class

#include <iostream>
using namespace std;
   
class Division {
    
  // for inputs
  int x, y;
   
public:
  // input numbers
  void input() {
    cout << "Input two integers\n";
    cin >> x >> y;
  }
  void performDivision() {
    //  division of both numbers
    cout << "Result: " << x / y << endl;
  }
};
   
// driver
int main()
{ 
   // object of class
    Division m; 
   
   m.input();
   m.performDivision();
   
   return 0;
}

Output:
Output depends on user inputs, that will be division 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]=4;
   a[1]=2;
  
   //  subtraction of first two elements
   a[2]=a[0] / a[1];
   cout<<" division of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
   return 0;
}

Output:

division of 4 and 2 is 2 

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.