Click here to Skip to main content
15,860,844 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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];

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.
Posted
Updated 25-Aug-09 10:19am
v2

1 solution

Consider this as a rough idea:

C++
#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. :)

 
Share this answer
 
v2
Comments
Niklas L 3-Jun-10 17:12pm    
That sounded like a homework to me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900