c++loopsfor-loopiomanip

Can't get Right aligned number triangle pattern giving space using setw in C++


I want a right aligned number pattern using setw for giving spaces either the spaces disappear when setw is less than no. of printed numbers or it makes any random pattern. My Code is below:

 #include <iostream>
 #include<iomanip>
 using namespace std;

 int main()
 {
   int space, n,i,j,k,l,m;
   cin>>n;

   for (k = n; k <=2*n-1; k++)
   {
        cout<<setw(k);
   }
   for(i=1;i<=n;i++){
     for(j=1;j<=i;j++){
        cout<<j;
     }
     cout<<endl;
   }
   return 0;
}

The output I am getting is (n=5):

        1
12
123
1234
12345

The output I want is (n=5):

    1
   12
  123
 1234
12345

Solution

  • The first for loop is not necessary.

    setw sets the field length for the next field (the field following setw). So if the next field is an empty string, setw(x) will just reserve x characters space. Also, the value x should be equal to n - i (if no. of characters to be printed is 1, you need (5 - 1) i. e. 4 spaces)

     #include <iostream>
     #include <iomanip>
     using namespace std;
    
     int main()
     {
       int n, i, j;
       cin >> n;
    
       for (i = 1; i <= n; i++) {
         cout << setw(n - i) << "";
         for (j = 1; j <= i; j++) {
            cout << j;
         }
         cout << endl;
       }
       return 0;
    }