How to center align a pattern?

448 views Asked by At

How can I align this arrow tail centered unded the arrow head?

    **
   ****
  ******
 ********
**********
****
****
****
****

Here is my code:

#include<iostream>
using namespace std;
int main() {
  int n;
  cout<<"enter size";
  cin>>n;

  int rows,columns;
  cout<<"enter numbers";
  cin>>rows>>columns;

  for(int k=1;k<=n;k++){
    for(int j=1;j<=n-k;j++){
      cout<<" ";
    }
    for(int j=1;j<=k;j++){
      cout<<"*";
    }
    for(int i=1;i<=k;i++){
      cout<<"*";
    }
    cout<<endl;
  }
  for(int i=1;i<=rows;i++){
    for(int j=1;j<=columns;j++){
      cout<<"*";
    }
    cout<<endl;
  } 
  return 0;
}

I try to run it with the following input:

enter size 5
enter numbers 4 4 

The arrow looks fine, but the tail is left aligned. How can I get it into the center?

1

There are 1 answers

0
Christophe On BEST ANSWER

Assuming you display fixed spaced characters on a terminal, the general algorithm is:

  • Take the width we of the element you want to center.
  • Take the width WA of the area it needs to be centered in
  • Print (WA-we)/2 whitespaces before the element

Considering that in your case WA would be 2*n and we would be columns, you could write somewhere:

 int s=(2*n-columns)/2;

and print in the second part of your algorithm s spaces before starting printing the * of your Christmas tree trunk.

By the way, I don't know if you're allowed to use string for your homework, but if yes, you could replace the loops for printing w characters c one after another with just printing string(w, c), (for example cout<<string(s, ' ');), which will make your programme more compact and readable.