Friday, June 18, 2021
Home coding Write a program to reverse an array.

Write a program to reverse an array.

Given a integer array ,we have to find reverse an array .and print their reverse values on screen.

Example:

input:arr[]={1,2,3,4,5}
output:5,4,3,2,1

Logic:

Step 1-create a temp variable.
Step 2-initalise low=0,high=n-1
Step 3-start swapping till (low<high) satisfy.

Code-

#include<bits/stdc++.h>
using namespace std;
void reverse(int arr[],int n)
{
    int low=0;
    int high=n-1;
    while(low<=high)
{
    int temp=arr[low];
    arr[low]=arr[high];
    arr[high]=temp;
    low++;
    high--;
}
}
int main()
{
    int arr[]={1,5,7,9,10};
    int n=sizeof(arr)/sizeof(arr[0]);
    reverse(arr,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
   
  
   
    
    
}

Output:

10 9 7 5 1 


Time complexity:0(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments