Click here to Skip to main content
12,508,185 members (55,470 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C++ C++/CLI C MFC ATL WTL STL
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 15-Aug-09 8:59am
sharp_k646
Updated 25-Aug-09 10:19am
v2

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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. :)

  Permalink  
v2
Comments
Niklas Lindquist 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160927.1 | Last Updated 25 Aug 2009
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100