DEV Community

Cover image for Three Simple Ways to Reverse an Array in C++
Mujahida Joynab
Mujahida Joynab

Posted on

Three Simple Ways to Reverse an Array in C++

The easiest way to reverse an array -

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    cin >> n;
    int a[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }``

    for(int i = n - 1 ; i >= 0 ; i--){
        cout << a[i] << " " ;
    }
}

Enter fullscreen mode Exit fullscreen mode

There is another way to reverse an array using single array

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    cin >> n;
    int a[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (int i = 0, j = n - 1; i <= j; i++, j--)
    {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
}
Enter fullscreen mode Exit fullscreen mode

There is another way to reverse an array using two array -

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    cin >> n;
    int a[n], b[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (int i = 0, j = n - 1; i < n; i++, j--)
    {
        b[j] = a[i];
    }
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    cout << "\n";
    for (int i = 0; i < n; i++)
    {
        cout << b[i] << " ";
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)