while loop to for loop

Can i know how to change while loop into for loop ?

1
2
3
4
5
6
 int x=10, y=0;
 while(x-- > 0)
{
 if(x % 2==0)
     y++;
}
1
2
3
for( int x{ 10 }; x > 0; x-- ) {
    // ...
}
@integralfx thanks for the reply. erm.. I still don't understand your code, Sorry can it be more specific ? :)
You can read about while loops and for loops in the tutorial here:
http://www.cplusplus.com/doc/tutorial/control/

Basically, any while loop
1
2
3
4
    while (condition)
    {
        // do something
    }

can be written as a for loop:
1
2
3
4
    for (      ; condition;    )
    {
        // do something
    }


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.
Last edited on
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.
@Chervil @joe864864 Thanks for the reply. Both were good explanation ! :D
Topic archived. No new replies allowed.