arraysc

Why do array element values not change?


int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

for (int i = 0; i <= 9; i++) {
    int tmp = a[i];
    a[i] = a[9 - i];
    a[9 - i] = tmp;
}

for (int i = 0; i <= 9; i++) {
    printf("%d", a[i]);
}

The result of it is: 1234567890, but why not 10987654321 since it switch values in the first for loop, but why can not change it when the next for loop runs

I have tried to move "int tmp" outside of the loop, but of no use at all.


Solution

  • Your loop:

    for(int i=0;i<=9;i++){
        int tmp= a[i];
        a[i] = a[9-i];
        a[9-i] = tmp;
    }
    

    Each iteration it swaps elements.

    On the first iteration, it swaps a[0] and a[9]. On the second a[1] and a[8] and so on.

    But what about the 10th iteration?

    Well, it swaps the values in a[9] and a[0]. But you already swapped those values, so it's just swapping them back the way they originally were.

    1 2 3 4 5 6 7 8 9 10
    10 2 3 4 5 6 7 8 9 1
    10 9 3 4 5 6 7 8 2 1
    10 9 8 4 5 6 7 3 2 1
    10 9 8 7 5 6 4 3 2 1 
    10 9 8 7 6 5 4 3 2 1 <-- This is what we want.
    10 9 8 7 5 6 4 3 2 1 
    10 9 8 4 5 6 7 3 2 1
    10 9 3 4 5 6 7 8 2 1
    10 2 3 4 5 6 7 8 9 1
    1 2 3 4 5 6 7 8 9 10
    

    If you stop after 5 (half the length of the array) iterations, you're only swapping each pair once and your code will behave the way you expect.


    To illustrate the suggestion from @user4581301 in comments, see below. We get begin and end pointers to the first and last elements in the array, respectively. Our loop continues as long as the begin pointer is less than the end pointer. If end is greater than begin it means we've gone past halfway. If they're equal, it means our array had an odd number of elements, and we've hit the middle one. That middle element wouldn't need to be swapped, so either way we're done.

    The update in the loop increments begin and decrements end, moving inward one place from each end of the array.

    #include <stdio.h>
    
    int main() {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
        int *begin, *end;
    
        for (
          begin = &arr[0], end = &arr[9]; 
          begin < end; 
          ++begin, --end
        ) {
            int temp = *begin;
            *begin = *end;
            *end = temp;
        }
    
        for (size_t i = 0; i < 10; ++i) {
            printf("%d\n", arr[i]);
        }
    }