Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to reverse an array.

C Code Example — Array Programs

ADVERTISEMENT

C Program to reverse an array.

Objective

Write a C program to reverse the contents of an array.

Algorithm / Approach

  1. Declare an original array orig[5] and a destination array rev[5].
  2. Read elements into the original array.
  3. Use a for loop with two counters: i starting at the end of the original array (4) and going down, and j starting at the beginning of the reversed array (0) and going up.
  4. Copy the elements: rev[j] = orig[i].
  5. Print the reversed array.
main.c
#include<stdio.h> 
int main( ) {
 int i, j;
 int orig[5], rev[5];
 printf("Enter array elements : ");
 for (i = 0; i < 5 ; i++){
   scanf("%d", &orig[i]);
 }
 for (i=4, j=0; i>=0; i--,j++){
   rev[j]=orig[i];
 }
 printf("Reverse array is : ");
 for (i = 0; i < 5; i++){
   printf("%d  ", rev[i]);
 }
 return 0;
}

Expected Output

Enter the array elements : 1 2 3 4 5
Reverse array is : 5  4  3  2  1

Explanation of the Program

  • Reversing an array using a secondary destination array is easy. You read from the back of the first array and write to the front of the second array.
  • Note: You can also reverse an array "in-place" without using a second array by swapping the first element with the last, the second with the second-to-last, stopping when you reach the middle.

Complexity

Time Complexity O(n)
Space Complexity O(n) - Since we allocate a second array.
ADVERTISEMENT