Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jun 9, 2024
Difficulty: Easy

Reverse Array in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Reversing an array is a basic concept in programming that involves changing the order of elements in an array so that the first element becomes the last, and the last element becomes the first. In C programming, an array is a collection of elements of the same data type, stored in contiguous memory locations. 

Reverse Array in C

In this article, we will discuss different approaches to reverse an array in C, which include using an additional array, swapping elements, and utilizing pointers. 

Possible Approaches

There are several ways to reverse an array in C. Let's see three different approaches:

  1. Declaring another array: In this approach, we create a new array and copy the elements from the original array in reverse order. We start by copying the last element of the original array to the first position of the new array, and continue this process until all elements are copied.
     
  2. Iteration and Swapping: This approach involves swapping elements within the original array itself. We initialize two pointers, one pointing to the start of the array and the other pointing to the end. We then swap the elements at these pointers and move the pointers towards each other until they meet at the middle of the array.
     
  3. Using pointers: In this approach, we use two pointers, one pointing to the start of the array and the other pointing to the end. We swap the elements at these pointers and move the pointers towards each other until they meet at the middle of the array. This approach is similar to the iteration and swapping approach, but it directly manipulates the memory addresses using pointers.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Declaring Another Array

One straightforward method to reverse an array in C is by declaring a second array to store the reversed elements. This approach involves creating a new array of the same size as the original and then copying the elements from the original array to the new one in reverse order.

Example :

  • C

C

#include <stdio.h>

void reverseArray(int arr[], int size) {
int reversedArr[size];
for (int i = 0; i < size; i++) {
reversedArr[size - 1 - i] = arr[i];
}

// Optional: Copying back to original array
for (int i = 0; i < size; i++) {
arr[i] = reversedArr[i];
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

reverseArray(arr, size);

printf("Reversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output

Reversed array: 5 4 3 2 1 



Explanation:

The function reverseArray takes an array and its size as parameters. It first declares a new array reversedArr of the same size. The for loop iterates through the array & places each element into the reversedArr from the end to the beginning. Optionally, the elements can be copied back to the original array to update it with the reversed elements directly.

Note : This method is simple & effective, but it uses additional memory for the second array, which might be an issue where we need to take care of the memory usage or wherever we need to save memory.

Iteration and Swapping

Another efficient way to reverse an array in C is by using the iteration and swapping approach. This method swaps the elements from the two ends of the array moving towards the center, which effectively reverses the array without the need for additional storage.

Example:

  • C

C

#include <stdio.h>

void reverseArrayInPlace(int arr[], int size) {
int temp;
for (int i = 0; i < size / 2; i++) {
temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

reverseArrayInPlace(arr, size);

printf("Reversed array in place: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output

Reversed array in place: 5 4 3 2 1 


Explanation:

The function reverseArrayInPlace works by iterating up to the middle of the array. During each iteration, it uses a temporary variable temp to swap the elements from the front & the back of the array. This approach does not require any extra space beyond the temporary variable used for swapping, making it more space-efficient than the previous method.

Note : This approach is useful when memory usage is a critical constraint, as it changes the array in place without additional memory usage.

Using Pointers

Using pointers to reverse an array in C is a powerful approach that uses direct memory access to modify the array elements. This method involves two pointers: one starting at the beginning of the array and the other at the end. These pointers move towards each other, swapping the elements until they meet in the middle.

Example:

  • C

C

#include <stdio.h>

void reverseArrayWithPointers(int *start, int *end) {

   int temp;

   while (start < end) {

       temp = *start;

       *start = *end;

       *end = temp;

       start++;

       end--;

   }

}

int main() {

   int arr[] = {1, 2, 3, 4, 5};

   int *start = arr;

   int *end = arr + sizeof(arr) / sizeof(arr[0]) - 1;

   reverseArrayWithPointers(start, end);

   printf("Reversed array using pointers: ");

   for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {

       printf("%d ", arr[i]);

   }

   return 0;

}

Output

Reversed array in place: 5 4 3 2 1 


Explanation

In the reverseArrayWithPointers function, start points to the first element of the array, & end points to the last. The while loop continues as long as start is less than end. Inside the loop, elements pointed by start & end are swapped using a temporary variable temp. After each swap, start is incremented & end is decremented, effectively reversing the array in place using pointer arithmetic, which is fast & efficient.

Note : This pointer method is useful in systems programming where control over memory & performance optimization is crucial.

Frequently Asked Questions

What is the most space-efficient method to reverse an array in C?

The most space-efficient method is the "Iteration and Swapping" technique, as it only requires a single temporary variable for swapping and does not use additional arrays.

Can these methods be used for arrays of any data type?

Yes, these methods can be applied to arrays of any data type, including integers, characters, and structures. The key is to ensure that the swapping logic correctly handles the data size of the array elements.

How do pointers enhance the efficiency of array manipulation?

Pointers allow direct manipulation of memory locations, reducing overhead and increasing the execution speed, especially useful in low-level programming where performance is critical.

Conclusion 

In this article, we learned about reversing an array in C programming. We discussed three different approaches: declaring another array, iteration and swapping, and using pointers. Each approach comes with their own advantage and disadvantage. With the help of these different techniques, you can efficiently reverse arrays in your C programs based on your specific requirements and constraints. Reversing arrays is a fundamental operation that you will see frequently in programming, and learning these approaches will help you boost your problem solving skills.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Topics covered
1.
Introduction
2.
Possible Approaches
3.
Declaring Another Array
3.1.
C
4.
Iteration and Swapping
4.1.
C
5.
Using Pointers
5.1.
C
6.
Frequently Asked Questions
6.1.
What is the most space-efficient method to reverse an array in C?
6.2.
Can these methods be used for arrays of any data type?
6.3.
How do pointers enhance the efficiency of array manipulation?
7.
Conclusion