如何按顺时针方向打印4x4阵列 [英] How to print an a 4x4 array in clockwise direction

查看:128
本文介绍了如何按顺时针方向打印4x4阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用高级循环吗?我考虑了好一阵子,但无法解决.示例:

Do I have to use advance loops? I thought about it for quite a while but could not figure it out. Example:

int numbs[4][4] = 
[1,2,3,4 
 5,6,7,8
 9,10,11,12
 13,14,15,16];


当我打印时,它应该像这样打印.

1 2 3 4,然后8,12,16,15,14,13,9,5,67,11,10(即顺时针方向).

该功能应为通用,适用于任何大小的矩阵.任何帮助将不胜感激.


When i print it, it should print like this.

1 2 3 4, then 8, 12,16, 15,14,13,9,5,67,11,10, (ie clockwise direction).

The function should be generic for any size matrix. Any help will be appreciated.

推荐答案

将其视为一个粗略的想法:

Consider this as a rough idea:

#include <stdio.h>

void PrintArrayClockwise(int *array, int rows, int columns)
{
	int r = 0;
	int rh = rows / 2;
	int i;
	while (r < rh)
	{
		for (i=r; i<(columns - r); i++) printf("%d ",array[(r*columns)+i]);
		printf("\n");
		for (i=r+2; i<=(rows-r); i++) printf("%d ",array[(i*columns)-1-r]);
		printf("\n");
		for (i=(columns-r-2); i>=r; i--) printf("%d ",array[((rows-r-1)*columns)+i]);
		printf("\n");
		for (i=rows-r-2; i>r; i--) printf("%d ",array[(i*columns)+r]);
		printf("\n");
		r++;
	}
}

int main()
{
	int numbs[16];
	int i;
	for (i=0; i<16; i++) numbs[i]=i+1;

	PrintArrayClockwise(numbs, 4, 4);

	return 0;
}

它应与不同大小的数组(正方形和不正方形)一起使用.我没有彻底检查它,但这应该是一个很好的起点. :)

It should work with arrays of different sizes, both square and not. I didn''t check it thoroughfully but it should be a good starting point. :)


这篇关于如何按顺时针方向打印4x4阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆