revers array in c
#include <stdio.h>
void reverseArray(int arr[], int size) {
int start = 0;
int end = size - 1;
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, size);
printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Explanation:
- In this code, we define a function reverseArray
that takes an integer array arr
and its size as parameters.
- We initialize two variables start
and end
to the first and last index of the array respectively.
- We also declare a temporary variable temp
to store the value during swapping.
- We use a while
loop to iterate until start
is less than end
.
- Inside the loop, we swap the values at arr[start]
and arr[end]
using the temporary variable temp
.
- Then, we increment start
and decrement end
to move towards the center of the array.
- After the loop ends, the array will be reversed.
- In the main
function, we create an array arr
with some values and calculate its size using sizeof
.
- We call the reverseArray
function passing the array and its size.
- Finally, we print the reversed array using a for
loop.