How to Reverse an Array in C

How to Reverse an Array in C

4 mins read1.5K Views Comment
Updated on Aug 28, 2023 10:36 IST

In this article, we will discuss three different methods (using loops, pointers, and recursion) to reverse an array in C.

2023_03_MicrosoftTeams-image-243.jpg

In C programming, Arrays are a useful data structure. It allows the storage of multiple values in a single variable instead of creating individual variables for each value. They are easy to use and hence, are used extensively in programs that need to store and manipulate large amounts of data efficiently. In this article, we will learn how to reverse an array in C using different methods. So, without further ado, let’s get started!

Table of Content

What are Arrays in C?

An array is a collection of elements of the same data type stored in contiguous memory locations. It can be thought of as a list of variables of the same type, with each variable identified by an index or a subscript.

The elements can be accessed using their index value (0 to len(array) -1).

Must Check: Top C Programming Online Courses and Certification

Must Check: Free C Programming Online Courses and Certification

Example: If len(array) = 5, we can access its elements using the index values 0, 1, 2, 3, and 4.

The syntax for declaring an array in C is as follows:


 
data_type array_name[array_size];
Copy code

Here, 

  • data_type is the type of data that the array will hold, 
  • array_name is the name of the array, and 
  • array_size is the number of elements that the array can hold. 

For example, to declare an array of 5 integers, we can use the following code:


 
int my_array[5];
Copy code

We can also initialize the values of the array elements at the time of declaration, like this:


 
int my_array[5] = {10, 20, 30, 40, 50};
Copy code
Learn Data Types in C Programming With Examples
Learn Data Types in C Programming With Examples
Data types are the type of data stored in a C program. Data types are used while defining a variable or functions in C. It’s important for the compiler to...read more
Variables in C Programming: Types, Scope, and Lifetime
Variables in C Programming: Types, Scope, and Lifetime
Variables in C Programming are a container to hold the value of a data type. They help the compiler to create memory space for the type of Variable. Each variable...read more
Tokens in C Programming
Tokens in C Programming
Tokens are the smallest unit in the C program. Every keyword or character or sequence of characters that you come across in C is a token. It is the smallest...read more
Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

β‚Ή4.24 K
6 weeks
β‚Ή475
6 weeks
– / –
45 hours
β‚Ή4 K
80 hours
– / –
1 month
– / –
40 hours
– / –
2 months
– / –
1 year
β‚Ή4 K
80 hours

Methods to Reverse an Array

There are various methods for reversing an array in C. In this article, we are going to look at the most commonly used ones:

Using C Loops to Reverse an Array

The following code demonstrates how a for() loop can be used in C to reverse an array:


 
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // initialize the array
int temp, i, j;
printf("Original array: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
for (i = 0, j = 4; i < j; i++, j--) { // loop to swap elements
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("\nReversed array: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Copy code

Output:

2023_03_image-78.jpg

Explanation

  • Initialize an array with some values and print original using for loop.
  • Use another for loop to swap
    • first and last element, second and second last, and so on until the middle of the array is reached
  • two loop variables (i and j) are used to keep track of elements to be swapped, temporary variable (temp) to hold the value of one of the elements during the swap.
  • Finally, print the reversed array using another for loop.

Using C Pointers to Reverse an Array

The following code demonstrates how pointers can be used in C to reverse an array:


 
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // initialize the array
int *ptr1, *ptr2, temp;
printf("Original array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
ptr1 = arr; // point to first element of array
ptr2 = arr + 4; // point to last element of array
while (ptr1 < ptr2) { // loop to swap elements
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
ptr1++;
ptr2--;
}
printf("\nReversed array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Copy code

Output:

2023_03_image-79.jpg

Explanation

  • first initialize an array arr and print the original array using a loop.
  • Declare two integer pointers ptr1 and ptr2, which points first and last elements of the array, respectively.
  • while loop is used to swap the values of the elements pointed to by the two pointers
    • increment the first pointer and decrement the second pointer until they meet at the middle of the array.
  • At every iteration of the loop, a temporary variable (temp) is used to hold the value of one of the elements during the swap.
  • Finally, print the reversed array using another for loop.

Using C Recursion to Reverse an Array

The following code demonstrates how pointers can be used in C to reverse an array:


 
#include <stdio.h>
void reverseArray(int arr[], int start, int end);
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // initialize the array
printf("Original array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
reverseArray(arr, 0, 4); // call recursive function to reverse the array
printf("\nReversed array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
void reverseArray(int arr[], int start, int end) {
if (start >= end) { // base case
return;
}
int temp = arr[start]; // swap elements
arr[start] = arr[end];
arr[end] = temp;
reverseArray(arr, start + 1, end - 1); // call function recursively with updated indices
}
Copy code

Output:

2023_03_image-80.jpg

Explanation

  • first initialize an array arr and print the original array using a loop.
  • Declare a recursive function reverseArray() that takes an array, a starting index start, and an ending index end as input.
    • function checks whether start is greater than or equal to end, which is the base case of the recursion.
    • If the base case is not reached, the function swaps the values of the first and last elements of the array and then calls itself recursively with the starting index incremented and the ending index decremented until they meet at the middle of the array.
  • Finally, reverseArray() function array is called with the appropriate arguments to reverse the array and then print the reversed array using another loop.

Conclusion

In this article, we have discussed how to reverse an array in c with three different methods. Hope this article will helps you to get a better understanding of array in C.

Happy Learning!!

FAQs

What is an array in C?

An array in C is a collection of elements of the same data type that are stored in contiguous memory locations. Each element can be accessed by its index.

How do I reverse an array in C?

To reverse an array in C, you need to swap the first element with the last element, the second element with the second-to-last element, and so on, until you reach the middle of the array.

Is it possible to reverse an array in place in C?

Yes, the above code reverses the array in place, meaning that it modifies the original array without creating a new one. This is done by swapping the elements of the array using a temporary variable.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio