In: Computer Science
MUST BE DONE IN C (NOT C++)
Using an array and a function, print the values of an array backwards. Please follow these guidelines:
- Setup your array manually (whichever values you want, as many as you want and whichever datatype you prefer).
- Call your function. You should send two parameters to such function: the array’s length and the array.
- Inside the function, go ahead and print the array backwards.
- Your function shouldn’t return anything
Reversal of an array in C:
In the code below, I have sent 4 parameters to the function: the array, the position of the first element of the array, the position of the last element of the array, and the length of the array.
The main, driver function passed the above parameters to the revArray function. The revArray function, reverses the array and prints the output itself without returning anything.
The inputs are entered manually in the following code.
Code:
void rev(int arr[], int start, int end, int length)
{
int temp, i;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
printf("Reversed array is \n");
for (i=0; i < length; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[] = {12, 23, 34, 45, 56, 67, 78, 89, 90};
int n = sizeof(arr) / sizeof(arr[0]);
rev(arr, 0, n-1, n);
}
Output: