for loop to while loop

Hi guys

below is a for loop"given by my lecturer" is the while loop "mine" below that equivalent? just want to make sure im on the right track.

1
2
3
4
5
6
7
8
9
 n = 10;

for (int i = 1; i <= n; i++)
{
   if(i < 5 && i != 2)
   {
      cout << 'X';
   }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
    int i;
    i = 1;

    while(i < 10)
        if(i < 5 && i != 2)
        {
            cout << 'x';
            i++;
        }
        else
        {
            i++;
        }

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const int n = 10 ;

/////////////////////  **** for loop **** ////////////////////////////
for( int i = 1 /*  for-init-statement */ ; i <= n /* condition */ ; i++ /* expression */ )
{
    //// for-loop body starts here ////
    if(i < 5 && i != 2)
    {
        cout << 'X';
    }
    //// for-loop body ends here ////

} // scope of i has ended here


/////////////////////  **** while loop **** ////////////////////////////
{ // need an extra block to limit the scope of i

    int i = 1 ; /*  for-init-statement */
    while( i <= n ) /* condition */
    {
        //// for-loop body starts here ////
        if(i < 5 && i != 2)
        {
            cout << 'X';
        }
        //// for-loop body ends here ////

        i++ ; /* expression */
    }
} // scope of i has ended here 
Thank you JLBorges
Topic archived. No new replies allowed.