-3

My code:


using namespace std;

int main()
{
    int n; 
    int total = 0;
    cout << "Enter a value: ";
    cin >> n;
    while (total + n <= 1000)
    {
        cout << total << " ";
        total = n + total;
        continue;
    }
}

I need to add the following condition: if int n<0 program must close with a break operator

svep
  • 1
  • I suggest testing your code before expanding it further. You might find it doesn't work as expected (unless it is expected that user only enters one number in the whole program). – Yksisarvinen Apr 09 '22 at 14:51
  • "program must close with a break operator" it is unclear what you mean by that. `if (n <0) return 0;` after taking input ? – 463035818_is_not_an_ai Apr 09 '22 at 14:54
  • That `continue;` doesn't do anything. The loop ends at the `}` immediately after it, so the behavior would be exactly the same without the `continue;`. `continue` skips code that follows it. If there's no code following it, it isn't needed. – Pete Becker Apr 09 '22 at 14:55
  • @Yksisarvinen yep, it is expected that user only enters one number in the whole program – svep Apr 09 '22 at 14:57
  • You should add a description of what the program is supposed to do then, my first guess was that it's supposed to read numbers in a loop until the sum exceeds 1000. – Yksisarvinen Apr 09 '22 at 14:57

1 Answers1

1

If you want to break out of the while loop you can use something like this:

while (total + n <= 1000)
    {
        cout << total << " ";
        total = n + total;
        if (n < 0) break;
    }

But because variable n does not change in the loop I suggest you use return before the while loop:

int n; 
int total = 0;
cout << "Enter a value: ";
cin >> n;
if (n < 0) return 0;
while(...){
...
}
user16965639
  • 176
  • 11