#include <stdio.h>
void reverse_array(int *ptr, int n) {
// Your logic here
// for (int i = 0; i < n/2; i++)
// {
// *(ptr + i) = *(ptr + i) ^ *(ptr + n - 1 - i);
// *(ptr + n - 1 - i) = *(ptr + i) ^ *(ptr + n - 1 - i);
// *(ptr + i) = *(ptr + i) ^ *(ptr + n - 1 - i);
// }
int *start = ptr;
int *end = ptr + n - 1;
while (start < end) {
int temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
int n;
scanf("%d", &n);
int arr[100];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
reverse_array(arr, n);
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if(i < n-1){
printf(" ");
}
}
return 0;
}
This version uses a temporary variable (`int temp`) to swap values
at the start and end of the array while iterating inward.
Reason for Choosing Temp Swap Over XOR Swap:
---------------------------------------------
✔️ Performance:
- Temp swap: 2 memory reads + 2 writes per iteration
- XOR swap: 3 reads + 3 writes (more CPU cycles)
- Temp swap generates simpler machine code, better pipelining
✔️ Safety:
- XOR swap has undefined behavior if start == end (middle of odd-sized array)
- Temp swap is safe in all cases, even with overlapping pointers
✔️ Compiler Optimization:
- Temp swap is easy to optimize into register operations
- XOR-based logic may not get the same level of optimization
✔️ Readability and Maintainability:
- Temp swap is easier to understand and modify
- XOR logic is obscure and error-prone
✔️ Memory Use:
- Temp swap uses 4 bytes extra (on stack) — negligible even in constrained environments
- Operates in-place, no dynamic allocation
Input
5 1 2 3 4 5
Expected Output
5 4 3 2 1