Division without Using Division Operator In C/C++, Algorithm
Division without Using Division Operator In C/C++, Algorithm
It is not very hard to write such a function “Division Between Two Numbers Using Without Using Division Operator” in C. To accomplish our motives we can create a user-defined function, where we will use only minus to get our division result. Algorithm is the main fact for those kinds of problems. However, the algorithm is very easy to understand.
Division-by-Division Operator:
1. 9 / 3
2. 9 / 5
3. 3 / 2
We know that a division is a combination of (numerator / denominator or divisor).
Think as a simple division as above, what we do is subtract the numerator (9) by the divisor (3) each time if the numerator is not less than the divisor (3).
numerator = numerator – divisor; // (if numerator is not equal or less than the divisor)
From that above algorithm, we can hence our code:
/* Code Written By Alim Ul Karim */ /* email : auk.junk@live.com */ #include <stdio.h> int division(int x, int y) { int quotient = 0; while (x >= y) { x -= y; // (if numerator is not equal or less than the divisor) quotient++; } return quotient; } void main() { int x = 9; int y = 3; //works fine for all positive numbers, but not for negative numbers int r = division(x ,y); // result 1 printf("%d" , r); } |
However, since we have a problem with the negative number so we can include 2 more conditions in our code to make it better.
Code for all numbers:
/* Code Written By Alim Ul Karim */ /* email : auk.junk@live.com */ #include <stdio.h> int division(int a, int b) { //approximate result of the division operation between a ,b using minus int quotient = 0; int result_in_minus = 0; //if one is positive and the other is negative the result would be in negative if ((a < 0 && b > -1) || (a > -1 && b < 0) ){ result_in_minus = 1; } //check if minus exist, make all positive if (a < 0){ a = a * (-1); } if (b < 0){ b = b * (-1); } //this condition works for positive numbers only while (a >= b) { a -= b; quotient++; } //if one is positive and the other is negative the result would be in negative if(result_in_minus == 1) { quotient = quotient * -1 ;} return quotient; } void main(){ int x = 9; int y = -3; // works for all numbers int r = division(x , y); printf("%d" , r); } |
- See also related links from Alim Ul Karim's Blog:
- Division Operation Using Minus Operator In C/C++, Algorithm
- Multiplication Algorithm Using Add Operator in C/C++
- Remainder / Modulus Using Add(+) and Minus(-) or Subtract(-) Operator in C/C++
SEO Labels:
Division Operation Using Minus Operator In C/C++, Algorithm
excelent alim
ReplyDeleteexcellent alim
ReplyDelete