The function takes an integer array and its length as input. Implement the function to return the array such that the array is reversed i.e the first element of the array occupies the last position, the second element occupies the second last position and so on.
Note:
The rearrangement is to be done in-place i.e you cannot use another array.
Assumption:
You may assume that array is of an even length.
Example:
Input:
2 4 6 8 20 15 10 5
Output:
5 10 15 20 8 6 4 2
PROGRAM
#include<iostream.h>
#include<conio.h>
int* ReverseArray(int* arr, int length)
{
int i=length,j,temp=0;
for(j=0;j<i;j++,i--) //loop to reverse array
{
temp = arr[j];
arr[j] = arr[i-1];
arr[i-1] = temp;
}
cout<<endl<<endl<<"Reversed Array"<<endl;
for(j=0;j<length;j++) //loop used to print reversed array
{
cout<<arr[j]<<endl;
}
return 0;
}
int main()
{
clrscr();
int arr[100],n;
cout<<"Enter the number of elements you want in an array : ";
cin>>n; //user declares the size of the array, note that maximum size is 100
cout<<"\n\nEnter Array elements"<<endl<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i]; //user enters array elements
}
*ReverseArray(arr,n); //array function is called
getch();
return 0;
}
Comments
Post a Comment