I am trying to print a hollow square, I wrote the following code:
#include <iostream>
using namespace std;
int main () {
int heigth;
cout << "Height: ";
cin >> heigth;
int width;
cout << "Width: ";
cin >> width;
for (int i = 1; i <= heigth; i++) {
for ( int j = 1; j <= width; j++) {
if (i == 1 || j == 1 || i == heigth || j == width) {
cout << " # ";
} else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
When I run it with h=5 and w=5, I get the following shape:
# # # # #
# #
# #
# #
# # # # #
Instead of the a normal square.
I tried to print the value of j, I discovered that in the middle iterations, it jumps from 1 to 5 directly.
Like this:
# 1 # 2 # 3 # 4 # 5
# 1 # 5
# 1 # 5
# 1 # 5
# 1 # 2 # 3 # 4 # 5
The numbers you see are the values of j. Why is this happening?
>Solution :
Your code is perfectly fine and so is the value of j. The only problem is that you’re printing " " while you should be printing " ". This is because " # " has 3 characters, so your space also should be 3 characters long.
Final Code:
#include <iostream>
int main() {
int heigth;
std::cout << "Height: ";
std::cin >> heigth;
int width;
std::cout << "Width: ";
std::cin >> width;
for (int i = 1; i <= heigth; i++) {
for (int j = 1; j <= width; j++) {
if (i == 1 || j == 1 || i == heigth || j == width) {
std::cout << " # ";
}
else {
std::cout << " "; // Replaced " " with " "
}
}
std::cout << std::endl;
}
return 0;
}
In the above code I’ve also removed the following line:
using namespace std;
..as it’s considered as bad practice. For more information on this, see why is "using namespace std" considered as a bad practice.