给定输出的逻辑是什么

时间:2019-04-17 03:28:53

标签: c++

这是图案程序的输出。我发现很难找到以下输出的逻辑。请用C ++编写代码...

输出:

1
2 9
3 8 10
4 7 11 14
5 6 12 13 15

1 个答案:

答案 0 :(得分:-1)

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin>>n;
    int arr[n+1][n+1];
    int st, ed, inc;
    int num = 1;
    for(int j = 1; j <= n; j++) {
        if(j%2==1) {
            st = j, ed = n+1, inc = 1;
        } else {
            st = n, ed = j-1, inc = -1;
        }
        for(int i = st; i != ed; i += inc) {
            arr[i][j] = num;
            num++;
        }
    }

    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= i; j++) {
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }

    return 0;
}

输入: 5

输出:
1
2 9
3 8 10
4 7 11 14
5 6 12 13 15