C++ Program To Reverse An Array

 To reverse an array we will swap first element with last element of an array, after that we will swap second element with second last element and so on.

reverse array, c++, c++ problem, c++ example, array


Program:

#include <iostream>
using namespace std;

void reverse(int arr[],int start,int end)
{
    if(start >= end)
    return;

    //swaping elements
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;

    reverse(arr,++start,--end);
}

int main()
{
    int arr[] = {1,2,3,4,5};
    int n = sizeof(arr) / sizeof(arr[0]);   //getting size of an array

    reverse(arr,0,n-1);     //function call

    cout << "Reversed array is:" << endl;
    
    for(int i = 0; i < n; i++)
       cout << arr[i] << " ";

    return 0;
}

Output:

Reversed array is:
5 4 3 2 1
C++ Program To Reverse An Array C++ Program To Reverse An Array Reviewed by Beast Coder on April 12, 2021 Rating: 5

No comments:

Powered by Blogger.