converting for loop to while loop

hi, i'm a beginner at programming. can anyone help me? i can't seem to convert my loop.

this is my for loop
int i = 1;
const char square = '&';

for (int i = 1; i <= n; i++)
{
cout << square;
for (int i = 1; i < n; i++)
cout << '\t' << square;
cout << endl;
}

this is my while loop
int i = 1;
const char square = '&';

while (i <= n)
{
cout << square;
while (i < n)
{
cout << '\t' << square;
i++;
}
i++;
}

is there a problem with the conversion?
The scoping rules for for-loops meant you could get away with using i as the control variable for the two loops. But they weren't actually the same variable.

1
2
3
4
5
6
7
8
9
10
int i = 1; // this i is never used!
const char square = '&';

for (int i /* a different i */ = 1; i <= n; i++)
{
    cout << square;
    for (int i  /* yet another i */ = 1; i < n; i++)
        cout << '\t' << square;
    cout << endl;
}


is clearer (well, to me) as

1
2
3
4
5
6
7
8
9
const char square = '&';

for (int i = 1; i <= n; i++)
{
    cout << square;
    for (int j = 1; j < n; j++)
        cout << '\t' << square;
    cout << endl;
}


or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const char square = '&';

int i = 1;
while (i <= n)
{
    cout << square;
    int j = 1;
    while (j < n)
    {
        cout << '\t' << square;
        j++;
    }
    i++;
}


That is, while scoping rules do allow you re-use variable names within nested for loops, it doesn't always help the human being who's reading the code!

Andy
Last edited on
Topic archived. No new replies allowed.