Summary: In this programming example, we will learn to reverse an array without using another array in C.

The logic of reversing an array without using another array is to swap elements of the first half with elements of the second half i.e. the first element with the last element, then the second element with the second last element, and so on, till the middle element of the array.

Reverse array without array

In programming, we use while loop with the condition i<j to implement the process described above. Because if i==j, it means it is the middle element of the array and the middle element doesn’t need to be swapped.

Steps to reverse an array without using another array in C:

  1. Initialize an array with values.
  2. Set i=0 to point to the first element and j=length-1 to point to the last element of the array.
  3. Run while loop with the condition i<j.
    1. Inside loop swap ith and jth element in the array.
    2. Increment i and decrement j.
  4. End Loop.
  5. Display the array and end program.

Here is the implementation of the steps in C:

#include<stdio.h>

//function to display array
void display(int array[], int length){
  for(int i=0; i<length; i++){
    printf("%d ",array[i]);
  }
  printf("\n"); 
}
 
int main(){
  /*
    *You can take input in array using loop and scanf
    *Here for simplicity, I have pre-initialized array
  */
  int array[] = {1, 2, 3, 4, 5};
  int temp, length = 5;

  int i=0;         //for pointing 1st element of the array
  int j=length-1;  //for pointing last element of the array

  //display original array
  printf("Original array:   ");
  display(array, length);


  while(i<j){
    //swap
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;

    //update i and j
    i++;  
    j--;  
  }

  //display reversed array
  printf("Reverse of array: ");
  display(array, length);

  return 0;
}

Output:

C Program to reverse array without using another array

The above program reverses an array (in-place) with a time complexity equal to O(n).

This is one of the methods using which we can reverse an array in the C programming language. Comment if you have any other suggestions.

Leave a Reply

five × 4 =