This program allows to simulate the operation of an integer division between 2 positive integers a and b entered, we divide the largest over the smallest without using the operator “/” and then display the quotient and the remainder.
Example 1:Division two numbers by static numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #include <stdio.h> #include <stdlib.h> // Recursive function to perform division (x / y) of two positive numbers // x and y without using division operator in the code unsigned division(unsigned x, unsigned y) { if (x < y) { printf("Remainder is %d\n", x); return 0; } return 1 + division(x - y, y); } // Wrapper over division() function to handle negative dividend or divisor int divide(int x, int y) { // handle divisibility by 0 if (y == 0) { printf("Error!! Divisible by 0"); exit(1); } // store sign of the result int sign = 1; if (x * y < 0) sign = -1; return sign * division(abs(x), abs(y)); } // main function to perform division of two numbers int main(void) { int dividend = 17; int divisor = 4; printf("Quotient is %d\n", divide(dividend, divisor)); return 0; } |
Example 2: Division of Two Numbers Entered by User Without Using Divide Operator in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; // Recursive function to perform division (x / y) of two positive numbers // x and y without using division operator in the code unsigned division(unsigned x, unsigned y) { if (x < y) { printf("Remainder is %d\n", x); return 0; } return 1 + division(x - y, y); } // Wrapper over division() function to handle negative dividend or divisor int divide(int x, int y) { // handle divisibility by 0 if (y == 0) { printf("Error!! Divisible by 0"); exit(1); } // store sign of the result int sign = 1; if (x * y < 0) sign = -1; return sign * division(abs(x), abs(y)); } // main function to perform division of two numbers int main(void) { int dividend; int divisor; cout << "Enter a dividend: "; cin >> dividend; cout << "Enter a divisor: "; cin >> divisor; printf("Quotient is %d\n", divide(dividend, divisor)); return 0; } |
Output: