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] << " " ;
}
}
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] << " ";
}
}
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] << " ";
}
}
Top comments (0)