Program to Reverse an Array Elements In Place.

Given an array of sizes n and we need to reverse all array elements in place and print the reverse array. 

Note: The task is to reverse the array in place so that when we print the same array the array elements should be in reverse order.

{2, 4, 8, 1, 9} --- Reverse --- {9, 1, 8, 4, 2}

Example:

Input: arr[] = {9, 2, 7, 3, 10}
Output: arr[] = {10, 3, 7, 2, 9}

Approach: Using Iterative way (Brute Force)

Steps to solve the problem:
  • Declare two variables, start = 0 and end = n-1 where n is the size of the given array.
  • Run a while loop and keep swapping arr[start] and arr[end] and after each swap increment the value of start = start + 1 and decrement the value of end  = end - 1
  • Break the loop condition as soon as start >= end.
Reverse an Array Elements.

C++ code Implementation:
//C++ code to reverse the array elements
#include<bits/stdc++.h>
using namespace std;

//function to reverse array
void reverseArray(int arr[], int n){

    int start = 0, end = n - 1;

    while(start < end){
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

int main(){
    
    int arr[] = {9, 2, 7, 3, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    reverseArray(arr, n);

    for(int i = 0; i < n; i++){
        cout<<arr[i]<<" ";
    }

    return 0;
}
Output:
10, 3, 7, 2, 9

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS