Reverse Order Array in CPP
In this c++ tutorial, we are going to discuss how to print an array in reverse order in O(n) time complexity and without using any temporary array. Let’s reverse an array in C++ without using any second array.
Print Array in Reverse Order in C++ without using another array
How to swap two values using a temporary variable
Suppose, we have to swap the value of variables a and b, as we directly can’t give the value of a to b and b to a.
So, we will use a third variable temp to swap value.
int temp;
temp=a; // temp will take the value of “a”, so “a” now become free
a=b; // “a” will now take the value “b”, so “b” now become free
b=temp; // “b” will take the value temp which was initial value “b”
So, “b” has now the value of “a” and “a” has value of “b”.
Algorithm to reverse an array in C++
- Take an array arr[] of size n.
- For each index in array arr[] till half swap the value of the element at index i with n-i-1, like swapping the value of the first element with last element, second with second last.
- Proceeding the above step till half the size of arr[] we will get final array in reverse order.
C++ code: printing an array in reverse order
#include<bits/stdc++.h> using namespace std; void reverse(int arr[], int n) { int i,temp; for(i=0;i<n/2;i++) { temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } } int main() { int n,i; cin>>n; int arr[n]; for(i=0;i<n;i++) cin>>arr[i]; reverse(arr,n); for(i=0;i<n;i++) cout<<arr[i]<<" "; }
Example:
INPUT
1 2 3 4 5
OUTPUT
5 4 3 2 1
Learn more tutorials,
Leave a Reply