Exercise from C++ How to program Cyber classroom 4th ed.

B

Bruce Lee 646

Write a program that reads in the size of the side of a square and then prints
a hollow square of that size out of asterisks and blanks. Your program should
work for squares of all side sizes between 1 and 20. For example, if your
program reads a size of 5, it should print

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


Am I supposed to type all of the possible outputs between 1 and 20 and use a
selection structure to choose which one? That's the only thing I can think of.
is there another way?
 
J

jbruno4000

Am I supposed to type all of the possible outputs between 1 and 20 and use a
selection structure to choose which one? That's the only thing I can think
of.
is there another way?

You just need to work out an algorithm that works in all cases. On the first
and last line you're printing out all '*', otherwise, you're printing out a '*'
for the first and last value and spaces in between. It's hard to write any code
without doing it for you so I write the basic shell below. It's all in the
algorithm!

#include <iostream>

using namespace std;

int main()
{
int max;

cout <<"Enter size of one side: ";
cin >> max;

for(int i = 0; i < max; i++)
{
if(i == 0)

if(i == (max -1))

otherwise;
}
return 0;
}
 
L

loupceuxl

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
int x,
counter = 1;

cout << "Please input an integer between 1 and 20 to form the sides of a
square: " << endl;
cin >> x;

while ( counter <= (x * x) ) {
if ( ((counter % x) == 1) || (counter < x) || (counter > x * x - x) )
{
cout << "*";
}
else if ( (counter % x) == 0 ) {
cout << "*\n";
}
else if ( ((counter % x) > 1) && ((counter % x) < x) ) {
cout << " ";
}
++counter;
}

cout << endl;
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top