Trying to make a while Loop that subtracts a number until it reaches desired value and if subtraction surpasses desired value, display it and stop

StackOverflow https://stackoverflow.com/questions/23312942

Question

I'm new to programming and to c++ so I know this is probably a silly question but I would really appreciate the help. just as the tittle says, I'm trying to make a subtraction while type loop that reaches a desired value, in this case: 0 The code uses two random numbers from the user input. The first number is the minuend, the second is the subtrahend However, the problem that I'm having is that if subtraction surpasses desired value, the loop will not display it and the user will see displayed a number higher value than 0. I want to fix so it displays the negative number closest to 0 and then stop. Here's the code:

#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;



cout <<" enter a: ";
cin >> a;
cout << "enter b: ";
cin >> b;


while ( a > 0 )
{
cout << a << '\n';
a= a-b;

}

return 0;
}

What am I doing wrong, how can I fix it? Thanks

Was it helpful?

Solution

You're printing a before decreasing it. Try switching the statements inside your loop like so:

while ( a > 0 )
{
    a = a - b;
    cout << a << '\n';
}

OTHER TIPS

You could just add

cout << a << '\n';

again after your loop - you know you have the right value then. Or you could possibly avoid duplicating that line by switching to using a do ... while loop.

Hi i just switched this code:

while ( a > 0 )
{
  cout << a << '\n';
  a= a-b;
}

to this and it worked as you explained:

while ( a > 0 )
{
  a= a-b;
  cout << a << '\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top