Search code examples
carraysswitching

switching two elements in an array


The level is basic so bear with me. There are a few similar topics but didn't find my luck there. What I'm trying to do is to find max element in a row and then put it in the place of last element of the same row, while the last element to be put in the place of the max one the program found.

So I've got this code in C, it's supposed to print the original array, do the magic and then print the modified array. It does find the max element in 1st row, puts it in the last place of the same row, but doesn't do the switch - the last element doesn't hop in the place of max element's. I know I did something dumb and plain simple, but I just can't find where the mistake is. Any help highly appreciated!

int main()
{
int a[3][4]={23,32,45,12,53,75,38,72,14,37,42,82}, i, j, t, l, max=a[1][0];
for(i=0;i<3;i++){
   printf("\n");
   for(j=0;j<4;j++){
       printf("%d ", a[i][j]);
   }
}
for(l=0;l<4;l++){
    if(a[1][l]>max){max=a[1][l];}
}
t=a[1][3];
a[1][3]=max;
max=t;
for(i=0;i<3;i++){
   printf("\n");
   for(j=0;j<4;j++){
       printf("%d ", a[i][j]);
   }
}    


return 0;
}

And here is what it returns (original array):

23 32 45 12
53 75 38 72
14 37 42 82

(modified array):

23 32 45 12
53 75 38 75
14 37 42 82


Solution

  • You also need to store the position of max:

    int max_pos = 0; //same as the initial max - a[1][0]
    for(l=0;l<4;l++){
        if(a[1][l]>max){max=a[1][l]; max_pos=l;}
    }
    

    Then when you switch them:

    t=a[1][3];
    a[1][3]=max;
    a[1][max_pos] = t;
    

    I assume you are aware this only happens for the second row. If you want to do it for all rows, you'll have to store the positions in an array.