Division and Remainder Without Using the "\" ,"%" Operators

Tuesday, July 19, 2011 0 Comments A+ a-

C++ program for Division and remainder without using the / and % operators

Division, just like multiplication, can be implemented without using its own division operator which is the character "/". This can be done through subtraction since division can be implemented as a series of subtraction.
In the code below, the while loop checks if the dividend is still greater than or equal to the divisor. If so, dividend will continue subtracting from itself the value of the divisor while quotient (initialized as 0) will increment by 1 each time. What remains for the dividend (lDividend) after the loop is the remainder of the division. 

Division without using / operator
Remainder without using % operator
#include <iostream>

using namespace std;

int main(void)
 int dividend, divisor, quotient, remainder;
 char stay;

 cout << "Input dividend: ";
 cin >> dividend;

 cout <<endl << "Input divisor: ";
 cin >> divisor;

 quotient = 0;

 // always subtract dividend with the divisor
 //until dividend is lesser than the divisor
 while (dividend >= divisor)
  dividend -= divisor;
  //quotient = count every time subtraction is done
 cout << endl << "The qoutient = " << quotient << endl;

 //remainder = the remaining value after a series of substraction
 remainder = dividend;
 cout << "The remainder = " << remainder << endl;

 //wait for an input before exit 
 cin >> stay;

 return 0;