一种程序,以三角波形式从1到n打印数字,而不使用额外的空间

时间:2016-05-09 09:44:10

标签: c++ arrays

我想以三角波形式打印从1到n(比如10)的数字。这是代码 -

#include <iostream>
using namespace std;

int main() {
    //code
    int n;
    cin>>n;
    int arr[3][10];
    int r=1,c=0,dir=-1;
    int i,j;
    for(i=0;i<3;i++){
        for(int j=0;j<n;j++){
            arr[i][j]=0;
        }
    }

    for(i=1;i<=n;i++){
        arr[r][c]=i;
        if(r==2 || r==0)dir = -dir;
        if(dir==1)r++;
        else r--;
        c++;

    }

    for(i=0;i<3;i++){
        for(j=0;j<n;j++){
            if(arr[i][j]==0)
              cout<<"  ";
            else cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }

    return 0;
}

此代码的输出

    2       6       10
  1   3   5   7   9
        4       8

使用数组是否可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

替换第三个循环的主体
if (arr[i][j] == 0)
    cout << ' ';
else
    cout << arr[i][j];
cout << ' ';

确实,您想要打印数字,但如果是0,则需要打印空格