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?