Hollow rectangle, with X at its center whenver the entered values are both ODD.

I was able to make a code that displays a rectangle, whenever I input the width and length. But I have a problem, there must be an "x" in the center of the hollow rectangle, whenever the user inputs an ODD length, and ODD width, for example, 5 by 7. Thanks.

my code:

#include<iostream>

using namespace std;

int main()
{
int length=0, width=0;
cout << "Enter the length of the hollow rectangle: ";
cin>>length;
cout << "Enter the width of the hollow rectangle: ";
cin>>width;
for(int i=0; i<length; i++)
{
for(int j=0; j<width; j++)
{
if(i==0 || i==length-1 || j==0 || j==width-1)
cout << "*";
else
cout << " ";
}
cout<<endl;
}
system("pause");
return 0;
}
So create two more variables, like say
int midWidth = width / 2;

Then write another if statement making use of those new variables.
1
2
3
4
5
6
7
if(i==0 || i==length-1 || j==0 || j==width-1)
  cout << "*";
else if ( ... )
  cout << "x";
else
  cout << " ";
}

@salem c
where will I insert it in the loop?
I just showed you where!

Just replace the ... with some logical expression that indicates the middle of the rectangle.
will it look like this ?

#include<iostream>

using namespace std;

int main()
{
int length=0, width=0, cwidth = width/2, clength = length/2;
cout<<"This program will print a hollow rectangle, using the user's desired length and width. "<<endl;
cout<<endl;
cout << "Enter the length: ";
cin>>length;
cout << "Enter the width: ";
cin>>width;
cout<<" "<<endl;
for(int i=0; i<length; i++)
{
for(int j=0; j<width; j++)
{
if(i==0 || i==length-1 || j==0 || j==width-1)
cout<<"*";
else
cout<<" ";
if(i==0 || i==length-1 || j==0 || j==width-1)
cout<<"*";
else if (...)
cout<<"x";
else
cout<<" ";
}
cout<<endl;
}
cout<<endl;
system("pause");
return 0;
}
Did you even program the original yourself or did you just find it on the web?

> cwidth = width/2, clength = length/2;
Riiight.

And now do that AFTER you have input values for width and length.


> if(i==0 || i==length-1 || j==0 || j==width-1)
Why is this there now twice?


Study this
1
2
3
4
5
6
7
if(i==0 || i==length-1 || j==0 || j==width-1)
  cout << "*";
else if ( i == 3 && j == 3 )
  cout << "x";
else
  cout << " ";
}
Topic archived. No new replies allowed.