# help- swap the first and last column of a two dimensions array

Printable View

• 12-09-2010
markip
help- swap the first and last column of a two dimensions array
Hello!!! I am new in programming and i think i might need you help. I am trying to swap the first column with the last. Can someone help? Here is the code:
Code:

```for (i=0; i<N; i++)         {for(j=0; j<M; j++)                 { temp = A[i][1];                   A[i][1] = A[i][M];                   A[i][M] = temp;}         }```
• 12-09-2010
tabstop
The first column is not #1 and the last column is not #M. Also you only need to switch once per row, not for every single element in the array.
• 12-09-2010
anduril462
Try A[i][M-1].

Indexes in C go from 0 to size-1. If your array has M columns in it, valid indexes are 0..M-1.
• 12-09-2010
markip
Quote:

Originally Posted by anduril462
Try A[i][M-1].

Indexes in C go from 0 to size-1. If your array has M columns in it, valid indexes are 0..M-1.

ok i did this
Code:

```for (i=0; i<N; i++)         {for(j=0; j<M; j++)                 { temp = A[i][1];                   A[i][1] = A[i][M-1];                   A[i][M-1] = temp;}         }```
but now in the results it swaps the second with the third column(i have a 2x3 array). I need to swap the first with the third...
• 12-09-2010
tabstop
Quote:

Originally Posted by markip
ok i did this
Code:

```for (i=0; i<N; i++)         {for(j=0; j<M; j++)                 { temp = A[i][1];                   A[i][1] = A[i][M-1];                   A[i][M-1] = temp;}         }```
but now in the results it swaps the second with the third column(i have a 2x3 array). I need to swap the first with the third...

Quote:

Originally Posted by tabstop
The first column is not #1 and the last column is not #M. Also you only need to switch once per row, not for every single element in the array.

I am obligated to type something "new" here. So: "new".
• 12-09-2010
anduril462
I didn't show you, but I stated that the indexes go from 0 to M-1. So your use of 1 for the first column is incorrect. It's index 0.

tabstop also brought up a good point. Ditch your inner for loop. It's totally useless since you never do anything with j in your swap code.
• 12-09-2010
markip
:D :) ok!!! I DID IT!!! you were right !!! THANK YOU THANK YOU THANK YOU all of you!!