A C++ question.

Recommended Videos

PrimaVita

New member
Apr 5, 2009
97
0
0
Okay, I know you have to make an array to get this but I forgot how to do the printing correctly. Was wondering if anyone could help me.
Here is the question,
C++ to print elements in a m x n matrix. Must print in a clockwise manner. Start from the element at the top left. No element is the matrix is to be printed twice. A matrix may have several elements with the same value. Okay to print the same value more than once, though noth the element that contains the value. The algorithm must be able to handle matrices with even and odd rows of numbers and columns. ex. 6x6, 2x4. The numbers printed should be, 1 2 3 4 9 14 19 1 17 16 11 6 7 8 13 12.
Thanks. I just keep blanking on what to do next.
 

Proteus214

Game Developer
Jul 31, 2009
2,270
0
0
I'm not entirely sure what you are asking for here, but I certainly hope that you aren't asking for someone to do your homework for you since that would entirely defeat the purpose of the exercise. Are you not sure of how to write the algorithm? Is there a certain bit of syntax that you are stuck on?
 

burningdragoon

Warrior without Weapons
Jul 27, 2009
1,935
0
0
You really need to think out your question better. I (mostly) understand what you are asking, but your post is nonsense in terms of thought flow. 2D array and nested for loops is what you are looking for I believe.
 

Tharwen

Ep. VI: Return of the turret
May 7, 2009
9,145
0
41
So your matrix looks like this:

Code:
1  2  3  4
5  6  7  8
9 10 11 12
...and you want to print "1 2 3 4 8 12 11 10 9 5 6 7"?
 

PrimaVita

New member
Apr 5, 2009
97
0
0
Sorry about that guys. No it is not a homework assignment. I was thinking about using nested for loops but I went the matrix way. All I need to do is figure out to switch different numbers in different sequences when it is cout. That is the part that I am having trouble figuring out.
 

GrindBass

New member
Jun 7, 2009
74
0
0
The way I would go about printing clockwise (assuming its in the way that tharwen said since I didnt entirely understand your last post), assuming you've used a 2D array A for the matrix is this:

int left = 0, top = 0, right = m-1, bottom = n-1;
while(true)
{
if(left > right)
break;

for(int i=left; i <= right; i++)
std::cout << A[top];

top++;

if(top > bottom)
break;

for(int i=top; i <= bottom; i++)
std::cout << A
;

right--;

if(left > right)
break;

for(int i=right; i >= left; i--)
std::cout << A[bottom];

bottom--;

if(top > bottom)
break;

for(int i=bottom; i >= top; i--)
std::cout << A
;

left++;
}


Note that I have been drinking and have not tested this so there's probably something wrong with it (besides the fact the an infinite loop is normally a bad idea) :)