Do while loop prints only one number instead of 10

I put the condition that until x is equal to -10 keep on decrementing. Why does the code only display 1?


[/code]#include <iostream>
using namespace std;

int main()
{
int x = 1;

do {
cout << x << endl;
x--;
} while (x == -10);
return 0;
}
Well, if you require x to be equal to -10 in order to keep on looping ... then it won't keep looping!

Probably you meant
while ( x != -10 );
Or even this:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
    int x = 1;

    do {
            cout << x << endl;
            x--;
    } while (x >= -10);
    return 0;
} 


Why does the code only display 1?
Before I forget. The code only does what you told it to do :)
Last edited on
while means while, not until
A pointless and misleading comment given ‘until’ properly refers to the ‘=‘ part of the conditional contained in brackets which in turn relies on how @OP is expected to interpret their exercise question which is anybody’s guess.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

#define until(a) while (!(a))

int main()
{
   int x = 1;
   do
   {
      std::cout << x << '\n';
      x--;
   } until ( x == -10 );
}


1
0
-1
-2
-3
-4
-5
-6
-7
-8
-9


Actually, I'm slightly staggered that that runs!
Last edited on
Exactly, the name of the function has absolutely no bearing on the exit value whatsoever.
With the "accidental" operator:

1
2
3
4
5
6
7
8
9
#include <iostream>

int main(){ 
    constexpr int end {-10};
    int x{1};
    while (x-->end){
        std::cout << x << "\n";
    }
}


Edit:

Theoretically, if the bounds are known, use a for loop; save while loops for when there is a more complex boolean expression.

1
2
3
4
5
6
7
#include <iostream>

int main(){ 
    for (int x{1};x >= -10; x--) {
        std::cout << x << "\n";
    }
}
Last edited on
LOL.

Sounds like this is taking on a life of its own. Perhaps someone will now come in and say <vector>'s or some other STL component should have been used, not to forget const, constexpr, smart pointers, and, gods-forbid, what Herb Sutter has drivelled on about on YouTube. Perhaps there's even room for volatile or recommendations on stack vs heap memory usage to shave off a nanosecond.
Topic archived. No new replies allowed.