malik727
malik727

Reputation: 189

Division Without Using Arithmetic Operator

I am trying to create a program that performs INTEGER division between two numbers. The special thing is that this program will only use increment ++ or decrement -- operator and loops to perform the division.

int quotient = 0; 
while (num1 >= num2) 
{ 
   num1 = num1 - num2 ; 
   quotient++ ; 
} 

In the above code segment i am using the - operator where as I only want to use ++ or -- (i.e, no arithmetic operator except increment/decrement) to achieve the division between two numbers.

Upvotes: 2

Views: 782

Answers (2)

Jain Rishav Amit
Jain Rishav Amit

Reputation: 112

Instead of subtracting num2 from num1 using - operator, Add one more loop that will run from 1 to num2 and will decrease num1 by 1 using num1--

This will work :

int quotient = 0; 
while (num1 >= num2) 
{ 
   for(int i=1;i<=num2;i++){
        num1--;
   }
   quotient++; 
} 

Upvotes: 4

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123243

Write a function that implements subtraction by only using --

int subtract(int a, int b);  // returns a-b

Then use that instead of the built-in operator-:

int quotient = 0; 
while (num1 >= num2) 
{ 
   num1 = subtract(num1,num2); 
   quotient++ ; 
} 

Upvotes: 3

Related Questions