Thread: Printing different messages depending on the value of a variable in a for loop

1. Printing different messages depending on the value of a variable in a for loop

Beginner here so bear with me. This is what I have so far:

Code:
#include <iostream>

using namespace std;

int main()
{
int x = 0;

if (x == 1000) {
cout<<"X is finally equal to 1000.\n";
}
else {
for (; x <= 1000; x++)
{
cout<<"X is equal to " << x << ".\n";
}
}
cin.ignore();
}
What I want this to do is increment x by 1 repeatedly and print the current value of x at any given time until it reaches 1000, in which case it should add the word "finally". When I compile and run this code it increments x all the way up to 1000 but when it reaches 1000 it simply prints "X is equal to 1000.", ignoring the condition of the if statement that encloses it.

I think the problem is that the for loop wants to increment x until x is less than or equal to 1000, but at that point I want the if function to take over, and print its message. I'm not really sure how to go about doing that. 2. Put the if() inside the for() 3. Originally Posted by Salem Put the if() inside the for()
Thanks. Could you explain exactly why it has to be in that order? Because to me the most logical thing to do is check whether x is equal to 1000 and if it's not, increment it. 4. Because you can't just list things you need to do in any random order.

You put the "if x is 1000" first, before the loop executes. So you get exactly 1 shot at that being true, and then the code moves on to execute the for loop, never again to compare x with 1000.

Try this
Code:
for ( x = 0 ; x <= 1000 ; x++ ) {
if ( x == 1000 ) {
cout<<"X is finally equal to 1000.\n";
} else {
cout<<"X is equal to " << x << ".\n";
}
} 5. Originally Posted by Salem Because you can't just list things you need to do in any random order.

You put the "if x is 1000" first, before the loop executes. So you get exactly 1 shot at that being true, and then the code moves on to execute the for loop, never again to compare x with 1000.

Try this
Code:
for ( x = 0 ; x <= 1000 ; x++ ) {
if ( x == 1000 ) {
cout<<"X is finally equal to 1000.\n";
} else {
cout<<"X is equal to " << x << ".\n";
}
}
Makes sense. Thanks a lot for your help. 6. Originally Posted by ex-mortis Thanks. Could you explain exactly why it has to be in that order? Because to me the most logical thing to do is check whether x is equal to 1000 and if it's not, increment it.
Because a program is executed sequentially. Your if statement is executed before the loop (when x == 0).
The loop compromises all of the statements in the enclosing braces of the for (that is, the if is outside the loop!).
Btw, you should indent properly. Popular pages Recent additions 