J-J J-J - 1 year ago 73
C++ Question

How to display numbers by line depending on the number in C++?

Hi I am new to C++ and I am having problem with displaying the numbers from 1,2,3, and so on depending on the user input.

For example, if input is 3, first line of output should be 1, next line should be 2 3, and the last line should be 4 5 6. Please see below screenshot:

enter image description here

Answer Source

The number of elements to display in the leftmost n columns is exactly:


So, the numbers in the first row form the A000124 integer sequence.

Therefore, you can just add the row index to respective value of the sequence, and print it only when row index is not greater than column index.

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            if(i <= j) {
                cout << j*(j+1)/2+1 + i;
            cout << '\t';
        cout << endl;
    return 0;

See the code live.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download