C Program to Reverse an Array

Here we’ll see how we can write a C program to reverse an array. If an array is ’43 23 45 11 8 54 89′, then after reversal it will become ’89 54 8 11 45 23 43′. We’ll start will a simple approach – will reverse the array with help of an another array. We’ll copy the last element of the original array to the first element of the new array. Similarly, second last will be copied to the second element and so on. After we complete this process, the new array will have all the elements in reversed order. Then we’ll replace the original array with the new reverse array.

C Program to Reverse Array

#include <stdio.h>

void reverse_array(int* arr, int size) {
  int i;
  int arr1[124];

  /*Coping the array into a temporary array in reverse order...*/
  for (i = 0; i < size; i++) {
	arr1[i] = arr[size -1 - i];
  }
  
  /*Copying the reverse array into the original one...*/
  for (i = 0; i < size; i++) {
	arr[i] = arr1[i];
  }
}

int main() {
  int n;
  int i;
  int arr[128];
  printf("Enter number of elements: ");
  scanf("%d", &n);
  
  /*Taking the array as input from user...*/
  for (i = 0; i < n; i++) {
    printf("Enter %d-th element: ", i);
    scanf("%d", (arr+i));
  }
  
  /*Printing the input array...*/
  printf("The input array: ");
  for (i = 0; i < n; i++) {
    printf(" %d", arr[i]);
  }
  printf("\n");
  
  reverse_array(arr, n);
  
  /*Printing the array after reversing...*/
  printf("The reversed array: ");
  for (i = 0; i < n; i++) {
    printf(" %d", arr[i]);
  }
  printf("\n");
  return 0;
}

This program first takes input of an array and passes that array to the reverse_array() function. The reverse_array() function reverses the array using the logic mentioned above.

Here is the output.

reverse an array

The above reverse_array() function works well except it is bit inefficient. It takes help of another array, that means requires more memory. It also traverses the array twice.

Improved Logic

We can reverse the array without using any other array. Also we don’t have to traverse the array twice. We can swap the first element and the last element, second and the second last element and so on. We have to iterate upto the middle element.

Here is the improved reverse_array() function.

void reverse_array(int* arr, int size) {
  int i, tmp;

  for (i = 0; i < size/2; i++) {
	tmp = arr[i];
	arr[i] = arr[size -1 - i];
	arr[size -1 - i] = tmp;
  }
}

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0