Oct 30, 2021 at 6:25am Oct 30, 2021 at 6:25am UTC
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;
}
Oct 30, 2021 at 6:52am Oct 30, 2021 at 6:52am UTC
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 );
Oct 30, 2021 at 8:11am Oct 30, 2021 at 8:11am UTC
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 Oct 30, 2021 at 8:12am Oct 30, 2021 at 8:12am UTC
Oct 30, 2021 at 2:02pm Oct 30, 2021 at 2:02pm UTC
while means while, not until
Oct 30, 2021 at 6:11pm Oct 30, 2021 at 6:11pm UTC
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.
Oct 30, 2021 at 8:25pm Oct 30, 2021 at 8:25pm UTC
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 Oct 30, 2021 at 8:26pm Oct 30, 2021 at 8:26pm UTC
Oct 30, 2021 at 11:09pm Oct 30, 2021 at 11:09pm UTC
Exactly, the name of the function has absolutely no bearing on the exit value whatsoever.
Oct 31, 2021 at 2:41am Oct 31, 2021 at 2:41am UTC
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 Oct 31, 2021 at 2:50am Oct 31, 2021 at 2:50am UTC
Oct 31, 2021 at 3:12am Oct 31, 2021 at 3:12am UTC
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.