Reputation: 1515
while (x >= 1000)
{
cout << "M";
x -= 1000;
}
Can someone explain to me how this while loop works? I understand the condition is for x is greater or equal to 1000, it will print out 'M'.
The part after that is what I actually don't understand, is it saying that it will keep subtracting a thousand from X and keep printing until the condition is false?
Upvotes: 0
Views: 485
Reputation: 11787
while (x >= 1000) //x is greater than or equal to 1000
{ //executes loop if condition true, else the statement after the loop block
cout << "M"; // print M
x -= 1000; // x = x-1000
} //goes back to condition checking
Upvotes: 1
Reputation: 67075
Yes, that is exactly what it will do.
This translates roughly into:
While x is greater than or equal to 1000, do what is in the code block (over and over until the condition fails)
The code block then prints M and sets x equal to itself minus 1000. (x -= 1000
is the same as x = x - 1000
Hypothetical:
x = 3000
x is greater than 1000
print M
x is set to 2000
loop resets and checks x...passes test
print M
x is set to 1000
loop resets and checks x...passes test because of = portion
print M
x is set to 0
loop resets and checks x...fails
moves to the code after the while code block
Upvotes: 2
Reputation: 258588
The program appears to be an inefficient way of writing
x %= 1000;
which is x = x%1000
, where %
is the modulus operator.
Your code reaches the same result by subsequent substraction, and stops when x<1000
.
Upvotes: 0
Reputation: 100527
Yes.
it saying that it will keep subtracting a thousand from X and keep printing until the condition is false
Upvotes: 0