The original example could be written as a for loop maybe like this,
1 2 3 4 5 6
int x=10, y=0;
for ( ; x-- > 0; )
{
if(x % 2==0)
y++;
}
or perhaps like this:
1 2 3 4 5 6 7
int x, y;
for (x=10, y=0; x-- > 0; )
{
if(x % 2==0)
y++;
}
It is tempting to go further, and to put either or both the x-- and/or the y++ in the last section of the for statement, or maybe declare x and y in the first section, but that would change the meaning of the code so in this case I wouldn't do that.
Maybe a simpler example could help. So using a while loop your code could look like:
1 2 3 4 5 6
int input = 10, x = 0;
while (x < input)
{
cout << "Hi" << endl;
x++;
}
This simply outputs Hi ten times. In order to make this a for loop your code would look like:
1 2 3 4 5
int input = 10;
for (int x = 0; x < input; x++)
{
cout << "Hi" << endl;
}
This code outputs the same thing but does it differently. A for loop allows you to combine the initialization of the counting variable, the test, and the incrementation of the counting variable. Hope this helps.