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?