Using a while loop to get a square

Oct 4, 2019 at 1:35am
Hi everyone,

One my project is creating a hollow square. The steps are:
tell user to input an even number and a character
then display the hollow square equal the input.
for example if user input 4
* * * *
* *
* *
* * * *


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
#include <iostream>
#include <iomanip>

using namespace std;
int main()
{

	
	char ch;
	int num, x = 0, y = 1; 
	
	cout << "Enter a character and number:  ";
	cin >> ch >> num;

	if (num % 2 == 0)
	{
		while (x < num)
		{
			while (y < num)
			{
				cout << ch << endl;
				y++;
			}

			cout << ch << " ";
			x++;
		}

	}

}


So far I can only think of making half a box. Is there anything I'm missing ?
Last edited on Oct 4, 2019 at 1:36am
Oct 4, 2019 at 2:06am
From what I can see, what you’d get for something like '* 6' would be something like
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
*
*
*
*
*
* *
*
*
*
*
* *
*
*
*
*
* *
*
*
*
*
* *
*
*
*
*
* 


Your logic is just a little off. Try putting the endl in the outer loop and maybe check when you are under the top line of characters and over the bottom line, and then not print the char.

you probably want to switch x and y too.
Oct 4, 2019 at 3:02am
Hmmmm could you explain a little bit about the logic here ?
Oct 4, 2019 at 4:39am
Let's take a look at things.

You know that it's going to be a square, so...

Input:

* 6


Output:

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


From the output, you know that only two lines will have N number of characters
on the square: the top and bottom of the square. The rest will just have two
characters on the sides. (see below)


* * * * * *     <- a full line of N characters
*         *  <- two characters on side
*         *  <- two characters on side
*         *  <- two characters on side
*         *  <- two characters on side
* * * * * *     <- a full line of N characters


By knowing that you have to print two lines, you can then use a loop to print
the "hollow" part of the square. And you already know how many "hollow" lines
to print: it is num - 2, because we take two off to account for the top and
bottom sides of square that will be printed.
1
2
3
4
5
6
7
8
9
10
11
12
13
int num, x = 0;

...

if(num % 2 == 0) // accepting only even-numbered squares
{
    // First line, we will print a full line of N characters

    // The middle area here, we will print the hollowed area of the square

    // Last line is the same as the first, we will print a full line of N
    // characters, thus closing the square
}


It's probably easier to use a for loop than a while loop for this sort of
thing. Or at least my experiences.
Oct 5, 2019 at 12:47am
Wow thank you for the explanation. I don't think you couldn't be any clearer.
Topic archived. No new replies allowed.