蛇形数组打印(两种形式)

#蛇形数组打印
##第一种形式

  • 形式1
5
    1    2    3    4    5
   16   17   18   19    6
   15   24   25   20    7
   14   23   22   21    8
   13   12   11   10    9
请按任意键继续. . .
  • 形式2
5
   13   14   15   16    1
   12   23   24   17    2
   11   22   25   18    3
   10   21   20   19    4
    9    8    7    6    5
请按任意键继续. . .
  • 形式3
5
    9   10   11   12   13
    8   21   22   23   14
    7   20   25   24   15
    6   19   18   17   16
    5    4    3    2    1
请按任意键继续. . .
  • 形式4
5
   13   12   11   10    9
   14   23   22   21    8
   15   24   25   20    7
   16   17   18   19    6
    1    2    3    4    5
请按任意键继续. . .

完整代码

#include<iostream>
#include<stdlib.h>
#include <iomanip>

using namespace std;
/*打印函数*/
void my_printf(int arr[100][100],int num)
{
	int i, j;
	for (i = 0; i < num; i++)
	{
		for (j = 0; j < num; j++)
		{
			cout << setw(5) << arr[i][j];
		}
		cout << endl;
	}
}

int main()
{
	int arr[100][100] = { 0 };
	int i, j;
	int x, y;
	int num = 0;
	int count = 1;
	/*1的起始位置*/
	arr[x = 4][y = 0] = 1;
	cin >> num;//打印的列数
	/*判断起始位置的下一个数组是0&&没有越界。就置1*/
	for (i = 0; i < num*num; i++)
	{
		while (arr[x][y+1] == 0 && y + 1 < num)
			arr[x][++y] = ++count;
		while (arr[x+1][y] == 0 && x + 1< num)
			arr[++x][y] = ++count;
		while (arr[x][y-1] == 0 && y - 1 >= 0)
			arr[x][--y] = ++count;
		while (arr[x-1][y] == 0 && x - 1>= 0)
			arr[--x][y] = ++count;

	}
	my_printf(arr,num);

	system("pause");
}

##第二种形式

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

完整代码

#include<iostream>

using namespace std;

int main()
{
	int N = 0;
	while (cin >> N) 
	{
		int i, k;
		int x = 1;
		int count = 1;
		for (i = 1; i <= N; i++)
		{
			count = x;
			cout << count;
			for (k = i + 1; k <= N; k++)
			{
				count = count + k;//首地址值
				cout << ' ';
				cout << count;
			}
			x += i;//1 2 4 7 11 计算每行第一个元素值
			cout << endl;
		}
	}
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值