Division and Remainder Without Using the "\" ,"%" 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) { //variables 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 quotient++; } 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; }
2 comments
Write commentsnice article for beginners.thank you.
Replywelookups C++
javacodegeeks
thank you so much ..u totally saved me ..keep making this useful info..students like me will appreciate it
Reply