Reverse an array in place, using pointers only.
What to build
A function that walks two pointers towards each other.
Requirements
- Write
void reverse(int *a, int n). - Use two pointers and pointer arithmetic, with no
[ ]inside the function.
Input
The first line has n. The second line has n whole numbers.
Output
The reversed numbers, separated by single spaces.
Constraints
n is from 1 to 100.
Example
Input:
4
1 2 3 4
Output:
4 3 2 1
Why it works
Comparing the two pointers tells you when they have crossed, and each swap puts two elements in their final places.
Examples
Example 1 · Input
4 1 2 3 4
Expected output
4 3 2 1
Example 2 · Input
1 9
Expected output
9
Hints
Hint 1
Make one pointer to the first element and one to the last.
Hint 2
Swap through them, then move them towards each other.
Hint 3
Stop when the pointers meet.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
void reverse(int *a, int n) {
int *left = a;
int *right = a + n - 1;
while (left < right) {
int temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
int main(void) {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
reverse(a, n);
for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);
printf("\n");
return 0;
}