🔁 Reversing an Array Using Recursion in C++





🔁 Reversing an Array Using Recursion in C++

Reversing an array is a classic programming problem often used to understand fundamental concepts like recursion. In this article, you’ll learn how to reverse an array using recursion in C++, step by step. We’ll also explore the logic, provide a clean code block, sample output.


📘 What You’ll Learn

  • Basics of recursion in C++

  • How to reverse an array using recursion

  • Dry run of the algorithm

  • Real-world use case

  • Optimized and readable code


📖 Introduction to Recursion

Recursion is a technique where a function calls itself to solve a problem. Instead of using loops, recursion breaks the problem into smaller chunks until a base condition is met. When used correctly, recursion makes code elegant and closer to mathematical logic.


🧠 Problem: Reverse an Array Using Recursion

The task is simple: take an array of integers and reverse it without using loops. Instead, use a recursive approach.


💡 How It Works

  1. Start with the first and last elements of the array.

  2. Swap them.

  3. Recursively call the function with the next pair of indices.

  4. Stop when the left index is greater than or equal to the right index (base case).


🧾 C++ Program (With Copyable Code Block)

Here’s the complete C++ code that demonstrates this approach:

#include <iostream>
using namespace std;

void reverseArray(int arr[], int start, int end) {
    if (start >= end)
        return;

    // Swap the elements
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;

    // Recursive call
    reverseArray(arr, start + 1, end - 1);
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

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

    cout << "Original Array: ";
    printArray(arr, size);

    reverseArray(arr, 0, size - 1);

    cout << "Reversed Array: ";
    printArray(arr, size);

    return 0;
}
  

🖥️ Sample Output

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

✅ Why This Code Works

The recursive function swaps the outermost elements and calls itself with the remaining inner elements. The base case halts recursion once the middle of the array is reached, ensuring all swaps are completed efficiently.


🚀 Real-Life Applications

  • Reversing datasets for analysis

  • Implementing undo-redo systems

  • Data structure manipulations (e.g., stacks and queues)


🎯 Final Words

Recursion may seem tricky at first, but with practice, it becomes intuitive. Reversing an array with recursion is a great exercise to build your logic and C++ fundamentals.

If you found this helpful, share it with your friends or bookmark it for later!



Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

⚙️ Update Cookie Preferences