Open In App

Reverse Array in C

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to write a C program to reverse an array. Reversing an array means changing the order of elements so that the first element becomes the last element and the second element becomes the second last element and so on.

reversing an array in c

Reverse an array

Algorithm

  1. Initialize two variables start = 0 as starting index and end = n-1 as the end index.
  2. Swap arr[start] and arr[end] till the start index is less than the end index.
  3. Update the start index as start + 1 and the end index as end – 1.

C Program to Reverse an Array

C




// Iterative C program to reverse an array
#include <stdio.h>
  
/* Function to reverse arr[] from start to end*/
void rvereseArray(int arr[], int start, int end)
{
    int temp;
    while (start < end) {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
  
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
  
    printf("\n");
}
  
/* Driver function to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, n);
    rvereseArray(arr, 0, n - 1);
    printf("Reversed array is \n");
    printArray(arr, n);
    return 0;
}


Output

1 2 3 4 5 6 
Reversed array is 
6 5 4 3 2 1 

Complexity Analysis

  • Time complexity: O(n), where n is the number of elements in the array.
  • Auxiliary space: O(1)

Refer to the complete article Write a program to reverse an array or string for more methods to reverse an array or string.

Related Articles



Last Updated : 31 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads