Kodewick
Start learning →
Starter←→0 / 50

Reverse an array

#035Startera[i] = a[j]5 min

Flip an array in place, without a second array: i starts at the front and j at the back; swap a[i] and a[j], then move both one step to the middle, and stop when they meet. 1 2 3 4 5 6 becomes 6 5 4 3 2 1. Finish reverse(a, n); the program flips one array with an even count and one with an odd count.

Should show
6 5 4 3 2 1
50 40 30 20 10
main.c
#include <stdio.h>

void reverse(int a[], int n) {
    int i = 0, j = n - 1;
    while (i < j) {
        // your code here: swap a[i] and a[j]
        i++;
        j--;
    }
}

void show(int a[], int n) {
    for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);
    printf("\n");
}

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6};
    int b[] = {10, 20, 30, 40, 50};
    reverse(a, 6);
    reverse(b, 5);
    show(a, 6);
    show(b, 5);
    return 0;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.