顺时针打印数组

题目:C++利用二维数组的方法打印一个n*n的数字螺旋方阵。这个数字方阵的特点是:以左上角1开始向下,数字以外圈向里按自然数顺序转圈递增,一直到中心位置的n2为止。例如n =3

1 8 7

2 9 6

3 4 5

源代码:

#include<iostream.h> 
#include<process.h> 
#include<iomanip.h> 
int main() 
{
	int N,*b,d,**a; 
	cout<<"please input a number of array:"; 
	cin>>N; 
	if((b=new int[N*N])==NULL) 
	{
		cout<<"can't allocate more memory."; 
		exit(1);
	} 
	a=new int *[N]; 
	for(int c=0;c<N;c++) 
		a[c]=new int[N]; 
	for(int a1=0;a1<N;a1++) 
		for(int a2=0;a2<N;a2++) 
			a[a1][a2]=0; 
		for(int i=0;i<N*N;i++) 
			b[i]=i+1; 
		if(N%2) 
			a[(N-1)/2][(N-1)/2]=N*N; 
		i=0; 
		for(d=0;d<N/2;d++) 
		{ 
			for(int j=0+d;j<N-1-d;j++) 
				a[0+d][j]=b[i++]; 
			for(int k=0+d;k<N-d-1;k++) 
				a[k][N-1-d]=b[i++]; 
			for(int l=N-d-1;l>0+d;l--) 
				a[N-1-d][l]=b[i++]; 
			for(int m=N-1-d;m>=1+d;m--) 
				a[m][0+d]=b[i++]; 
		} 
		cout<<endl; 
		for(a1=0;a1<N;a1++) 
		{
			for(int a2=0;a2<N;a2++) 
				cout<<setw(4)<<a[a1][a2]; 
			cout<<endl; 
		} 
		return 0; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值