Printing hollow square and triangle

Hi guys. When it comes to printing rectangles (regular or inverted) and squares, the logic jumps into my mind and I can write the code pretty quickly. Here are some:

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
// Printing square made of *

#include <iostream>
using namespace std;
int main()
{
// Note: x is number of rows and y is number of columns

int i, j;
cout << "enter the number of rows of the rectangle MADE OF STARS you want: ";
cin >> i;
cout << "enter the number of columns of the rectangle MADE OF STARS you want: ";
cin >> j;

for(int x=1; x<=i; x++)
{
        for(int y=1; y<=j; y++)
        {
                cout << " * ";
        }
        cout << endl;
}
cout << "the size of the rectangle you entered is: " << i*j << endl;

return 0;
}




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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Printing regular or inverted triangles made of *

// Regular
#include <iostream>
using namespace std;

// x: number of rows entered by user, i: current row, j: stars
int main()
{

int x, i, j;
cout << "enter number of rows of right triaingle desired: ";
cin >> x;

for(i=1; i<=x; i++)
{
        for(j=1; j<=i; j++)
        {
                cout << "* ";
        }
        cout << endl;
}

return 0;
}


// Inverted
#include <iostream>
using namespace std;

int main()
{

int x, i, j;
cout << "enter number of rows of INVERTED right triaingle desired: ";
cin >> x;

for(i=x; i>=1; i--)
{
    for(j=1; j<=i; j++)
    {
        cout << "* ";
    }
    cout << endl;
}

return 0;
}




Now, to my question. When it comes to printing those SAME patterns but having them be hollow in the inside. How can I do that? I made a google search for some methods but they are all overly complicated (imo) and some use stuff I have not learned yet. So, my question is, can this be done using only loops and if-else statements??

Thanks
Last edited on
Within your existing inner loops, if you are at one of the limits in either i or j then print your symbol. Otherwise, print a blank space. That is your if-else construct.
Topic archived. No new replies allowed.