Flipping a matrix array

I'm trying to flip a 4x5 matrix so that the rows will be in reverse order.

For instance...
1 2 3
4 5 6
7 8 9
would turn into:
7 8 9
4 5 6
1 2 3

I got the first two rows to flip, but I can't get any more to change. Also I'm confused how matrices even work, if the equation is... source[r*col+c], and you're using a for loop such as (for i=0;i<col;i++), how does the matrix fill in high array values? Wouldn't i be equal to 0 very fast(if i was 4, wouldn't it simply stop after 4 loops and stop filling the array?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Example program
#include <iostream>
#include <string>
using namespace std;
void flipH(char source[], char dest[], int row, int coln);

int main()
{
char source[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'};
char dest[]={};
flipH(source,dest,4,5);
cout<<dest[0]<<" "<<dest[1]<<" "<<dest[2]<<" "<<dest[3]<<" "<<dest[4]<<" "<<endl;
cout<<dest[5]<<" "<<dest[6]<<" "<<dest[7]<<" "<<dest[8]<<" "<<dest[9]<<" "<<endl;
cout<<dest[10]<<" "<<dest[11]<<" "<<dest[12]<<" "<<dest[13]<<" "<<dest[14]<<" "<<endl;
cout<<dest[15]<<" "<<dest[16]<<" "<<dest[17]<<" "<<dest[18]<<" "<<dest[19]<<" "<<endl;


return 0;
}
void flipH(char source[], char dest[], int row, int coln){
    int count=0;
	for(int i = 0; i < row; i++){
			for(int j = 0; j < coln; j++){
				dest[count] = source[(row-1-i)*coln + j];
				count++;
			}
	}
}


Line 10. How large is the dest?
Thank you that fixed it. Can anyone explain to me how the logic behind "source[(row-1-i)*coln + j];" works though? I don't see how as i/j go up it's producing the correct value for dest.

For example, when count is 7 i and j are also both 7. At this point, shouldn't the for loop end since j is greater than coln, and my for loop states "j<coln"?

Also, as for the math. How does this make sense? For count 7... (row-1-7)*coln-7

So 4-1-7=-4*5-7=-20-7=-27? How is source[-27] the same as the value I want?
For example, when count is 7 i and j are also both 7.

Are they?

Lets replace your rows 12-15, because that is awful lot of repetition:
1
2
3
4
5
6
7
8
9
10
11
12
int count = 0;
const int Row = 4;
const int Col = 5;
for ( int i = 0; i < Row; ++i )
{
  for ( int j = 0; j < Col; ++j )
  {
    cout << '(' << i << ',' << j << ") [" << Col*i+j << ',' << count << "] " << source[count] << ' ';
    ++count;
  }
  cout << '\n';
}

What does that print, and how are i and j when count is 7?
Last edited on
Topic archived. No new replies allowed.