
173 views
Find Reverse of an Array in C Using Functions
To find the reverse of an array in C using functions, you can create a function that accepts an array and its size as arguments and then reverses the elements in the array. Here’s an example of how to do this:
C
#include <stdio.h>
// Function to reverse an array
void reverseArray(int arr[], int size) {
int start = 0;
int end = size - 1;
while (start < end) {
// Swap the elements at start and end positions
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Call the reverseArray function to reverse the array
reverseArray(arr, size);
printf("Reversed array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
In this example:
- We define a
reverseArray
function that takes an arrayarr
and its sizesize
as arguments. Inside the function, we use a two-pointer approach to swap elements from both ends of the array until we reach the middle. - In the
main
function, we ask the user to enter the size of the array and then input the elements of the array. - We call the
reverseArray
function to reverse the array. - Finally, we print the reversed array.
This program will reverse the elements of the array using the reverseArray
function and display the reversed array to the user.