Reverse an array

Reverse an array Dec. 19, 2020

Approach:

  • Store the input array.
  • Create a new array.
  • Fill it in reverse direction.

Result:

Size of an array: 5
Enter the array: 45 56 52 274 875
Previous Array: 45 56 52 274 875
Reversed Array: 875 274 52 56 45

C++ Program:

using namespace std;
#include <iostream>
int main()
{
    int n,i;
    cout << "Size of the array: ";
    cin >> n;
    int *arr = new int[n];
    int *reverse = new int[n];
    cout<<"Enter the array: ";
    for (i = 0; i < n; i++)
        cin >> arr[i];
    for (i = 0; i < n; i++)
        reverse[n - i - 1] = arr[i];
    cout<<"Previous Array: ";
    for (i = 0; i < n; i++)
        cout <<arr[i]<<" ";
    cout<<endl<<"Reversed Array: ";
    for (i = 0; i < n; i++)
        cout <<reverse[i]<<" ";
    free(arr);
    free(reverse);
}

Python Program:

list = input("Enter a list: ").split()
print(list)
list.reverse()
print(list)

Rate this post

Comments