Write a C Program To Reverse an Array Using Function
In this tutorial, we are going to see how to write a C program to reverse an array using function. For example, if ‘arr’ is an array of integers with three elements such as:
arr[0] = 1 arr[1] = 2 arr[2] = 3
Then, by reversing the array we will have:
arr[0] = 3 arr[1] = 2 arr[2] = 1
There are four ways to reverse an array in C, by using for loop, pointers, recursion, or by creating a function.
[st_adsense]
Write a C Program To Reverse an Array Using Function
#include <stdio.h> // function to reverse an Array void reverse(int arr[10], int n) { int i, tmp; for(i=0;i< n/2;i++) { tmp = arr[i]; arr[i] = arr[n-1-i]; arr[n-1-i] = tmp; } } int main() { int arr[100], i, size; printf("Enter size of array: "); scanf("%d",&size); printf("Enter the elements of the array: "); for (i = 0; i < size; i++) scanf("%d", &arr[i]); // call reverse function reverse(arr,size); // display reversed array printf("After reversing the array: "); for(i=0;i < size;i++) { printf("%d ", arr[i]); } return 0; }
Output:
Enter size of array: 3 Enter the elements of the array: 1 2 3 After reversing the array: 3 2 1
[st_adsense]