Basic problem with do loop

This is probably a stupid question but I keep making the same error whenever I create do while loops. Like the code below, my answers always goes 1 number past the specified condition. In this case, the output goes to 395 instead of stopping at the number less than 393, which should be 390.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main() {

int a = 2;
int sum;
int c;

do {
    a++;
    c = a* 5;
    cout << "Your number sum is : " << c << endl;
}
    while ( c < 393);

    return 0;
 }

By looking at it, I can see that when variable c reaches 390, it will still be less than 393 so, it will run again. Is there a way to fix it without changing the condition?...and without adding if statements?

Basically how do can I make it stop when c is no longer less than 393 if I didn't know that the previous number was 390 and the next number is 395?



It's not going to stop at 393, because you are incrementing by values of 5. It's always going to go past this Value the way the code is set up now. Try this:

while((c<393) || (a<=78));

Since 390 is 5*78, it won't go past 390.
Last edited on
This isn't a good candidate for a do while loop.

1
2
3
4
5
    while ( (c=a*5) < 393 )
    {
        ++a ;
        std::cout << "Your number sum is: " << c << '\n' ;
    }


or if you insist on the do while loop:

1
2
3
4
5
6
    c = a*5 ;

    do {
        cout << "Your number sum is : " << c << endl;
    }
    while ( (c = ++a * 5) < 393);
Topic archived. No new replies allowed.