代码:
#include <iostream>
using namespace std;
int main()
{
int n,a[20][20]={0};
cin>>n;
int p=0,q=0,i=0,j=0;
while(1){
if(n<=0){
break;
}
if(p==0&&q==0){
a[i][j]=n;
j=j+1;
p=1;
n--;
continue;
}
if(p==1&&q==0){
a[i][j]=n;
i=i+1;
j=j-1;
n--;
if(j==0){
q=1;
}
continue;
}
if(p==1&&q==1){
a[i][j]=n;
i=i+1;
n--;
p=0;
continue;
}
if(p==0&&q==1){
a[i][j]=n;
i=i-1;
j=j+1;
n--;
if(i==0){
q=0;
}
continue;
}
}
for(i=0;i<20;i++){
if(a[i][0]==0){
break;
}
for(j=0;j<20;j++){
if(a[i][j]>0){
cout<<a[i][j]<<" ";
}
}
cout<<endl;
}
return 0;
}
结果:
问题2:
输入n,是行数
输出:比如输入5
1 3 6 10 15
2 5 9 14
4 8 13
7 12
11
代码:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int n;
while(cin>>n){
int i=0,j=0,m=1;
int **p=new int* [n];
for(int m=0;m<n;m++){
p[m]=new int[n];
}
for(int k=0;k<n;k++){
for(int k1=0;k1<n;k1++){
p[k][k1]=0;
}
}
for(int k=0;k<n;k++){
for(int k1=0;k1<k+1;k1++){
p[i][j]=m++;
//cout<<i<<","<<j<<" ";
if(i!=0){
i=i-1;
j=j+1;
}
}
// cout<<endl;
i=k+1;
j=0;
}
int s1=n;
for(int k=0;k<n;k++){
for(int k1=0;k1<n;k1++){
if(p[k][k1]==0){
continue;
}else{
if(k1==s1-1){
s1=s1-1;
cout<<p[k][k1];
}else{
cout<<p[k][k1]<<" ";
}
}
}
if(k==n-1){
break;
}
cout<<endl;
}
}
return 0;
}
结果: