🔁reversing an array using loop c++






Reversing an Array Using Loop in C++

Reversing an array is one of the most fundamental tasks in programming. Whether you're preparing for a coding interview or building your logical skills, knowing how to reverse an array using a loop in C++ is essential.

This article explains how to reverse an array using a loop, provides a sample program, and highlights key takeaways. If you're a beginner or an intermediate coder, this guide is perfect for you.


📘 What You'll Learn

  • How arrays work in C++

  • Logic for reversing an array using a loop

  • How to implement it in C++

  • Sample output for better understanding


🔁 Reversing an Array – The Logic

To reverse an array using a loop:

  1. Start from both ends of the array.

  2. Swap the first and last elements.

  3. Move inward (increment the start index, decrement the end index).

  4. Continue until the two pointers meet.

This is a simple yet powerful algorithm that helps you manipulate data structures efficiently.


📋 C++ Program to Reverse an Array

Below is a clean and optimized C++ program using a loop to reverse an array. You can copy this code using the "Copy" button.



// C++ Program to Reverse an Array Using Loop
#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Reversing array using loop
    for (int i = 0; i < n / 2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - 1 - i];
        arr[n - 1 - i] = temp;
    }

    // Display reversed array
    cout << "Reversed Array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

💻 Sample Output

Reversed Array: 50 40 30 20 10


📝 Final Thoughts

Reversing an array using a loop in C++ is a must-know trick for anyone learning data structures. Not only is it helpful in real-world applications, but it's also a common interview question.

Keep practicing and explore variations like reversing only a portion of the array or using recursion!



Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences