To reverse an array in C, you can swap the elements in the array starting from the two ends and working towards the middle. Here is an example function that reverses an array of integers:
cvoid reverseArray(int arr[], int size)
{
int i, temp;
for (i = 0; i < size/2; i++)
{
temp = arr[i];
arr[i] = arr[size-1-i];
arr[size-1-i] = temp;
}
}
In the above code, arr
is the array to be reversed, and size
is the number of elements in the array. The function uses a for
loop to iterate over the first half of the array, swapping each element with its corresponding element from the end of the array.
You can call this function with an array and its size as arguments to reverse the array in place:
cint main()
{
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr)/sizeof(int);
reverseArray(arr, size);
// Now arr is {5, 4, 3, 2, 1}
return 0;
}
In the above code, the reverseArray
function is called with arr
and size
as arguments to reverse the elements in the array in place.
Comments
Post a Comment