This code is supposed to output a hollow square (size and symbols to be determined by the user), but it doesn't do that. First of all, if I set the size of the square to be 5, it outputs 10-5 sets of both symbols. Also the right column is in the middle of the square, not at the end. So right now my square of size 5 looks like this:

* + * + * + * + * + 
* +    * + 
* +    * + 
* +    * + 
* + * + * + * + * +

I need it to look like this:

*  +  *  +  *
+           +
*           *
+           +
*  +  *  +  *

Here is the code I have so far:

#include<iostream>
using namespace std;

int main()
{
    cout << "Please enter a size for the square: ";
    int size;
    cin >> size;
    cout << "Please enter first symbol: ";
    char sym1;
    cin >> sym1;
    cout << "Please enter a second symbol: ";
    char sym2;
    cin >> sym2;

    for (int row=1; row<=size; row++)
    {
        for (int col=1; col<=size; col++)
        {
            if (row>1 && row<size && col>1 && col<size)
                cout << " ";
            else
                cout << sym1 << " " << sym2 << " ";
        }
        cout << "\n";
    }

    return 0;
}

What am I doing wrong?

Recommended Answers

All 3 Replies

Check out this vs. what you have.

$ ./a.out
Please enter a size for the square: 5
Please enter first symbol: +
Please enter a second symbol: *
* + * + * 
+ * + * + 
* + * + * 
+ * + * + 
* + * + * 

Keep in mind that if odd the columns will alternate and if even it wont alternate down

$ ./a.out
Please enter a size for the square: 6
Please enter first symbol: +
Please enter a second symbol: *
* + * + * + 
* + * + * + 
* + * + * + 
* + * + * + 
* + * + * + 
* + * + * + 
Code
#include<iostream>
using namespace std;

int main()
{
    cout << "Please enter a size for the square: ";
    int size;
    cin >> size;
    cout << "Please enter first symbol: ";
    char sym1;
    cin >> sym1;
    cout << "Please enter a second symbol: ";
    char sym2;
    cin >> sym2;

    int other(0); 
    for (int row=1; row<=size; row++) {
        for ( int col(1); col<=size; col++){
           // This makes it go every other
           if ( other++%2 ){
              cout << sym1 << " ";
           } else{
              cout << sym2 << " ";
           }
        }
        cout << endl;
     }
     cout << "\n";

    return 0;
}

Also, to alternate the symbols (going down) if the size is even, just add 1 to other before the for loop.

Thanx for the help, but I needed the middle to be empty. I figured out a different way to do it in the end.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.