To reverse an array in C, you can swap elements from the start and end of the array using a loop until you reach the middle.
In this example,
intArray
containing integers.start
and end
to track the start and end indices of the array.start
to end
until start
is greater than or equal to end
(indicating we've reached the middle).#include <stdio.h>
int main() {
int intArray[] = {1, 2, 3, 4, 5};
int length = sizeof(intArray) / sizeof(intArray[0]);
for (int start = 0, end = length - 1; start < end; start++, end--) {
int temp = intArray[start];
intArray[start] = intArray[end];
intArray[end] = temp;
}
printf("Reversed Array: ");
for (int i = 0; i < length; i++) {
printf("%d ", intArray[i]);
}
return 0;
}
Reversed Array: 5 4 3 2 1
In this example,
strArray
containing strings.start
and end
to track the start and end indices of the array.start
to end
until start
is greater than or equal to end
(indicating we've reached the middle).#include <stdio.h>
#include <string.h>
int main() {
char* strArray[] = {"apple", "banana", "cherry"};
int length = sizeof(strArray) / sizeof(strArray[0]);
for (int start = 0, end = length - 1; start < end; start++, end--) {
char* temp = strArray[start];
strArray[start] = strArray[end];
strArray[end] = temp;
}
printf("Reversed Array: ");
for (int i = 0; i < length; i++) {
printf("%s ", strArray[i]);
}
return 0;
}
Reversed Array: cherry banana apple
In this tutorial, we learned How to Reverse an Array in C language with well detailed examples.