Hello DonnaPin,
For a learning experience. Reworking your code:
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 32 33 34 35
|
#include <iostream>
using namespace std;
int main()
{
int height = 10, width = 10;
for (int i = 0; i < width; i++)
{
cout << "#";
}
cout << endl;
for (int i = 1; i < height - 1; i++)
{
for (int j = 1; j < width; j++)
{
if (j == 1 || j == width - 1)
{
cout << "#" ;
}
cout << " ";
}
cout << endl;
}
for (int i = 0; i < width; i++)
{
cout << "#";
}
}
|
The first for loop you use
i <= width
. Take time to count this line and you will see that the "<=" prints 1 mote "#" than you need. The for loop starts at (0) zero, which is a good starting point for most things as C++ is a zero based language, but the "<=" does 1 more loop than you need.
Also this first for loop counts as the first line of "height" and the last for loop counts as a second line. So when you get to the nested for loops you only need 8 lines to print.
In the nested for loops, the outer loop use
for (int i = 1; i < height - 1; i++)
. The loop iterator starts at 1. This accounts for the first for loop and the first line. The "height - 1" accounts for the last line from the last for loop.
In the inner for loop I changed the if statement.
See what you think and if it makes more sense now.
Both
Furry Guy's and
seeplus's methods are good, but first it helps to understand what was wrong first before you get into some more advanced.
The output of the program is:
##########
# #
# #
# #
# #
# #
# #
# #
# #
##########
|
Now it is 10 columns X 10 rows.
Andy
Edit: