-3

Please help me, Im using codeblocks 16 and I dont know why this code doesnt print a square, is just a square! Another thing is how can I improve this code? Im still learning please dont be mad at me thanks so much for you time

#include <iostream>
using namespace std;
int main () {
    char a = 'a', d = ' ';
    int b = 0, c = 0;

    while (c < 5) {
        cout << a;
        c = c + 1;
    }
    cout << endl;
    c = 0;
    while (c < 3) {
        cout << a;
        while (b < 3) {
            cout << d;
            b = b + 1;
        }
        cout << a << endl;
        c = c + 1;
    }
    c = 0;
    while (c < 5) {
        cout << a;
        c = c + 1;
    }
    cout << endl;
    return 0;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Renato
  • 1
  • 3

2 Answers2

2

You forget to reinitialize b to 0.

Using for would be easier to read:

for(int c = 0; c < 3; ++c) {
    cout << a;
    for (int b = 0; b < 3; ++b) {
        cout << d;
    }
    cout << a << endl;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • thank you, this is so embarrassing... – Renato Jun 22 '16 at 00:17
  • In the future, add as much logging as you need to until you can figure it out. For example, before `while (b < 3) {` you could have temporarily added a line like `cout << "About to enter b while loop, b=" << b << endl;`. – David Schwartz Jun 22 '16 at 00:25
0

The issue is that you do not reset the value of b every time you loop through your outer loop. Thus, on the second row of the square (the first row with spaces), it works just fine. However, on the third row, as you get to the inner while loop, b still equals 3 from the previous pass through that loop.

If I may also make a suggestion at the same time, name your variables meaningfully, and the errors will become more obvious. I would recommend using variables row and column rather than b and c. Sometimes all you need is slightly clearer variable names, and the bug stands out.

Cort Ammon
  • 10,221
  • 31
  • 45