C Program to Reverse an Array using Recursion

In this article, we will write a C program to reverse an array using recursion. Reversing the array means, the first element of the array becomes its last element, the second element becomes the second last element, and so on.

Sample Example:

Input:     { 1, 2, 3, 4, 5 }
Output:  { 5, 4, 3, 2, 1 }

Input: {  1, 2, 3 }
Output: { 3, 2, 1}

Before we start writing the actual program, let’s try to understand what is recursion in computer programming.

In computer programming, recursion is a concept where a function calls itself over again and again until it matches a certain condition.

The condition after which the function stops calling itself is known as a base case. The recursive function must have at least one base case, otherwise, it will continue calling itself infinitely.

See implementation in the following C program:

// C Program to reverse an array using recursion

#include <stdio.h>
#include <conio.h>

// Function to reverse the array
void reverse(int arr[], int start, int end){
	
	// Base case
	if(start >= end){
		return;
	}
	
	// Swap array elements at index start and end
	int temp   = arr[start];
	arr[start] = arr[end];
	arr[end]   = temp;
	
	// Call the function itself
	reverse(arr, start + 1, end - 1);
}

int main() {
	
	// Initialize the array
	int arr[] = {1, 2, 3, 4, 5};
	
	// Calculate the size of the array
	int length = sizeof(arr)/sizeof(arr[0]);
	
	printf("Original Array: ");
	for(int i = 0; i < length; i++){
		printf("%d ", arr[i]);
	}
	
	// Call the reverse() function to reverse the array
	reverse(arr, 0, length - 1);
	
	printf("\nReversed Array: ");
	for(int i = 0; i < length; i++){
		printf("%d ", arr[i]);
	}
	
	return 0;

}

Output:

Original Array: 1 2 3 4 5
Reversed Array: 5 4 3 2 1

Program Explanation:

In the above example, we have created a recursive function reverse(), which takes three arguments: the array that we want to reverse, the starting index of the array and the ending index of the array.

The recursive function checks if the starting index is greater than or equal to the ending index. If yes, it returns from there and stops further calls.

If not, it first swaps the array elements that are at indexes start and end and then again calls itself by incrementing the starting index by 1 and decrementing the ending index by 1.

This continues until the value of start and end becomes equal.

That’s how this program works.

I hope you will find this article helpful. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

Leave a Comment