0
int n, o = 2;
            
cout << "n="; cin >> n;
            
for(int i = 1; i <= n; i++) {
    for(int j = n; j >= i; j--) {
        cout << o << " ";
        o += 2;
    }
    cout << endl;
}

My code outputs (when n is 4)

2 4 6 8 
10 12 14 
16 18 
20

How would I align it to output this?

2  4  6  8 
  10 12 14 
     16 18 
        20

I am trying to align the output to the right in such a way that the numbers are aligned one below another (for example the 4 is aligned to the space between the 10 and 12 and I want to align it to 10). Thanks.

1
  • 1
    Check std::right and std::setw Commented Oct 8, 2022 at 20:06

2 Answers 2

3

The header <iomanip> provides many input/output manipulators you can play with, one beeing std::setw, which sets the width parameter of the stream for the next item.

Changing the line in the posted snippet that outputs the numbers into

std::cout << std::setw(3) << o;

The output becames

  2  4  6  8
 10 12 14
 16 18
 20

Now, to produce the desired output, we can notice that the first number of each row can either be printed with an increasing "width" (3 the first row, 6 the second and so on) or after a loop that prints the right amount of spaces (0 the first row, 3 the second and so on).

Sign up to request clarification or add additional context in comments.

Comments

1

just edited the inner loop of your code and this is the edited code:

#include <iostream>
using namespace std;
int main() {
    int n, o = 2;

    cout << "n="; cin >> n;

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (j >= i) {
                cout << o << "\t";
                o += 2;
            }
            else
            {
                cout << "\t";
            }
        }
        cout << endl;
    }
}

and this is some example output:

n=4
2       4       6       8
        10      12      14
                16      18
                        20

what I did is to make the inner loop, loops from 1 till n like the outer loop and only check if the current column is greater than or equal to the current row, if so, then I print the number and increment it, if not then I just cout a space or a tab to be more specific

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.