blacklotus
blacklotus

Reputation: 17

How to print inverted half-star pyramid pattern next to each other?

I want to display an inverted half-star pyramid pattern next to each other.Here's the desired output

And here's my code:

#include <iostream>
using namespace std;
int main()
{
  int n, x, y, k;
  cout << "Enter Number of Rows: ";
  cin >> n;
  for (x = n; x >= 1; x--)
  {
        for (y = 1; y <= x; y++)
        {
              if (y <= x)
                    cout << "*";
              else
                    cout << " ";
        }
        for (y = n; y >= 1; y--)
        {
              if (y <= x)
                    cout << "*";
              else
                    cout << " ";
        }
        cout << "\n";
  }
  return 0;

}

Here's the output I got after running the code. The number of rows desired is 10. After running my code, the output isn't like what I expected. Please tell me how to make it right. Thank you.

Upvotes: 0

Views: 867

Answers (2)

Karan Singh
Karan Singh

Reputation: 253

Well, you need to change your logic a little bit rest all is fine.

Here is the code:-

#include <iostream>
using namespace std;

int main()
{
    int n, x,  y, k;
    cout << "Enter the number of Rows: ";
    cin >> n;

    for(x = 1; x <= n; x++)
    {
        for(y = n; y >= 1; y--)
        {
            if(y <= x)
                cout << " ";
            else
                cout << "*";
        }

        for(y = 1; y <= n; y++)
        {
            if(y <= x)
                cout << " ";
            else
                cout << "*";
        }
        cout << "\n";
    }
    return 0;
}

Explanation:- I am starting from row 1 and going till row "n". Now I need to print two different inverted flags so I used two for loops for that. In one loop I am starting from column "n" and going till row >1 and in the other loop, I am doing the just opposite of that so that both flags will be opposite to each other. Just try to understand this code by taking X as row and Y as column.

Upvotes: 0

James Owen
James Owen

Reputation: 21

I saw some symmetries in the problem

  • for n rows, we're printing 2*n+1 characters
  • for the yth row, we're printing an asterisk if x is less than n-y or more than n+y

So I coded a single double loop with the more complex if statement. I had to adjusted the if statement until it worked.

#include <iostream>
using namespace std;
int main()
{
    int n, x, y;
    cout << "Enter Number of Rows: ";
    cin >> n;

    for (y = 0; y < n; y++)
    {
        for (x = 2*n+1; x > 0; x--)
        {
            if ((x > n+y+1) || (x < n-y+1))
                cout << "*";
            else
                cout << " ";
        }
        cout << "\n";
    }
    return 0;
}

Upvotes: 2

Related Questions