Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse an integer array in C [duplicate]

Tags:

arrays

c

Given an integer array with 5 elements [1,2,3,4,5], I am attempting to reverse the order of the elements in the array; e.g. the array would become [5,4,3,2,1].

int main(void) {
    int n = 5; //Num of elements
    int arr[5] = {1,2,3,4,5};
    for (int i = 0; i < n; i++) {
        printf("%d\n", arr[i]); //Print original vals
    }
    n--; //Decrement n by 1 for simplicity
    for (int i = n; i >= 0; i--) {
        int temp = arr[n - i]; //Set temp the max-index (4) - i
        printf("\nSmall: %d\nBig: %d\n", arr[n - i], arr[i]); //Print current temp & arr[i]
        arr[n - i] = arr[i]; //Set arr[max-index - i] to arr[i] (e.g arr[0] = arr[4]) 
        arr[i] = temp; //Set arr[i] to arr[max-index - 1] (e.g. arr[4] = arr[0])
        printf("\nBig: %d\nSmall: %d\n", arr[n - i], arr[i]); //Print new set
    }
    for (int i = 0; i < n + 1; i++) { //Print array in reverse order
        printf("%d\n", arr[i]);
    }
    return 0;

}

The first for loop should print:1 2 3 4 5 and the last: 5 4 3 2 1

However, it prints 1 2 3 4 5 both times, but the print statements in the loop that reverses the array prints the right numbers. Have I done something wrong?

Should I be dynamically allocating memory or something else not allowing me to change the array?

like image 583
Leshawn Rice Avatar asked Jan 23 '26 07:01

Leshawn Rice


1 Answers

The problem is, you swap every element twice (unless it is the center one) which ultimately does not swap anything. At the first loop, you technically swap first and last item. At the last loop, you did the same. So, you reverse the first action, returning the item back to original position.

Another problem is you try to access arr[5] which is undefined as your array is of size 5 and thus the index should be from 0 to 4 only.

Following is a function reversing the array:

void ReverseArray(int arr[], int size)
{
    for (int i = 0; i < size/2; i++)
    {
        int temp = arr[i];
        arr[i] = arr[size - 1 - i];
        arr[size - 1 - i] = temp;
    }
}
like image 115
lamandy Avatar answered Jan 25 '26 19:01

lamandy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!