Reverse an Array
Reverse an Array in C++ (7 Programs With Output)
BeginnerTopic: Array Operations Programs
C++ Reverse an Array Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = 5;
// Method 1: Using reverse() from algorithm
int arr1[] = {1, 2, 3, 4, 5};
reverse(arr1, arr1 + n);
// Method 2: Using swap
int arr2[] = {1, 2, 3, 4, 5};
for (int i = 0; i < n / 2; i++) {
swap(arr2[i], arr2[n - i - 1]);
}
cout << "Original array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "Reversed (method 1): ";
for (int i = 0; i < n; i++) {
cout << arr1[i] << " ";
}
cout << endl;
cout << "Reversed (method 2): ";
for (int i = 0; i < n; i++) {
cout << arr2[i] << " ";
}
cout << endl;
return 0;
}Output
Original array: 1 2 3 4 5 Reversed (method 1): 5 4 3 2 1 Reversed (method 2): 5 4 3 2 1
Understanding Reverse an Array
This program demonstrates 7 different methods to reverse an array: using reverse() algorithm, using swap, using two pointers, using recursion, using stack, using temporary array, and using vector.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.