Hello.. I finished a program that does multiplication by successive addition.. But now I want to change my program to do division by successive subtraction? I tried to change my while loop to break out sooner but it didn't work... Thanks for any Help!

``````#include<iostream>
using namespace std;

int div(int m, int n){
int sum = 0;
while(n != 0){
sum = m - sum;
n = n - 1;
}
return sum;
}

int main(){
int m, n;
cout<<"Enter two numbers: ";
cin>>m>>n;
cout<<div(m,n)<<endl;
return 0;
}``````
3
Contributors
2
Replies
4
Views
9 Years
Discussion Span
Last Post by Colin Mac

I think your algorithm has some problems. In this line:

``while(n != 0)``

you are already deciding how many times you are going through the loop. n has been passed to div. So if n was 5, you're going to go through the loop 5 times? Not true. You don't know how many times you are going to go through the loop. That's what you are trying to find out. Set a loop counter to start at 0. Increment it every pass through the loop. The loop control should be something like:

``while (m >= 0)``

n will be subracted from m each time through the loop. Your loop counter will be incremented each time (you'll have to create a variable other than m or n for that loop counter). The loop counter will be what is returned from the function div.

Division by subtraction is how many times a number can be subtracted from a number until
you're left with nothing.

eg 6/3 = 2. Three can be subtracted from six twice.

Therefore you should be incrementing a value from zero, after each subtraction.

``````while( num != 0)
{
num = num - num2;
result++;
}``````

This will only work as long as the numbers can be divided evenly, so you'll need to come up with something better if odd numbers are entered.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.