plotter
plotter

Reputation: 9

Why is the second column of the square not printed in its excepted place?

sorry if the question isn't clear enough so here I am explaining more:

#include <iostream>

using namespace std;

int main()
{
    int num;
    cout << "Enter a number: ";
    cin >> num;

    for (int y = 1; y <= num; ++y){
        for (int x = 1; x <= num; ++x){
            if (x == 1 || x == num || y == 1 || y == num){
                cout << "* ";
            }

        }
        cout << endl;
    }
}

This piece of code is supposed to print a square shape (framed), it's doing well except for the second column is being dragged to the left with the first column. Here how it looks like (actual output):

* * * * * * * *
* *
* *
* *
* *
* *
* *
* * * * * * * *

and my expected output is supposed to look like this:

* * * * * * * *
*             *
*             *
*             *
*             *
*             *
*             *
* * * * * * * *

Any help? especially that I don't see any problem with my code!

Upvotes: 0

Views: 46

Answers (1)

cigien
cigien

Reputation: 60238

You're not printing any spaces when you're not printing asterisks. Just add printing for that case as well:

if (x == 1 || x == num || y == 1 || y == num) {
    cout << "* ";
}
else {
    cout << "  ";  // to align the * to the right
}

Here's a demo

Upvotes: 2

Related Questions