How to center an output?

How can I be able to create a program when the user inputs n=4
the output should be like this

*
**
***
****
Well since your dealing with a stream and not a gui you can't easily "center" it on the screen, but you can pad the left side of each line with white space. Try to figure the rest out yourself, but feel free to ask if you really have trouble getting it.
@Mathhead200: Yes, what i meant is padding the left side of each line with white space where in my example, line4 touches the left side of the screen. How can I do that? I really don't have an idea.

this is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{int n, i=0, j=0;
cout<<"Enter n: ";
cin>>n;
for(i=1;i<=n;i=i+1)
{for(j=1;j<=i;j=j+1)
cout<<"*";
cout<<endl;}
system("pause");
}

but it sticks to the left side.
you have to know how wide the terminal display is.
what os are you using? (and what os is your professor using?)

you might just do ok to assume 80 characters wide...
Would this program work for you?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main (){
    int qtyOfLines;
    cout << "Qty of Lines? ";
    cin >> qtyOfLines;
    
    for(int i=0; i<qtyOfLines; i++){
        for(int j=0; j<(qtyOfLines-i-1); j++){
          cout << " ";  
        }
        
        for(int j=0; j<i+1; j++){
          cout << "* ";  
        }
        cout << endl;
    }

    system("pause");
    return 0;
}
Last edited on
I suggest looking into including iomanip and using std::setw().

You just mean like this, right? (Not centered on the console, just padded to form an isosceles triangle.)
  *
 ***
*****


...just add spaces before printing the asterisks. For a 3 row triangle: the first line has 2, the second line has 1, the third line has 0.
   *    (n is 1 or 0*2 + 1,  pad is 3 or 4 - 1 - 0)
  ***   (n is 3 or 1*2 + 1,  pad is 2 or 4 - 1 - 1)
 *****  (n is 5 or 2*2 + 1,  pad is 1 or 4 - 1 - 2)
******* (n is 7 or 3*2 + 1,  pad is 0 or 4 - 1 - 3)
Topic archived. No new replies allowed.