225k views
4 votes
Write a function SwapArrayEnds() that swaps the first and last elements of the function's array parameter. Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}.

User Smonff
by
7.5k points

1 Answer

1 vote

Answer:

This c++ program swaps the first and last elements of the array.

#include <iostream>

using namespace std;

void SwapArrayEnds(int a[], int k);

int main() {

int len, arr[len];

int j;

cout<<"Enter the size of array" <<endl;

cin>>len;

cout<<"Enter the elements of the array"<<endl;

for(j=0; j<len; j++)

{

cin>>arr[j];

}

cout<<"The elements of the array before swapping are"<<endl;

for(j=0; j<len; j++)

{

cout<<arr[j]<<"\t";

}

SwapArrayEnds(arr, len);

return 0;

}

void SwapArrayEnds(int a[], int k)

{

int temp=a[0];

int l;

a[0]=a[k-1];

a[k-1]=temp;

cout<<endl<<"The elements of the array after swapping are"<<endl;

for(l=0; l<k; l++)

{

cout<<a[l]<<"\t";

}

}

OUTPUT

Enter the size of array

6

Enter the elements of the array

12

34

56

78

90

23

The elements of the array before swapping are

12 34 56 78 90 23

The elements of the array after swapping are

23 34 56 78 90 12

Step-by-step explanation:

This program accepts user input for both size and elements of the array.

The first and the last element of the array are swapped in another method, SwapArrayEnds.

This method accepts an integer array and another integer variable which shows the size of the array.

The method which accepts parameters is declared as shown.

void SwapArrayEnds(int a[], int k);

In the above declaration, void is the return type. The parameter list contains one integer array followed by the length of that array.

This method is defined as below.

void SwapArrayEnds(int a[], int k)

{

// first element of the array is assigned to another variable

int temp=a[0];

int l;

// last element of the array is assigned to the first index, 0, of the array

a[0]=a[k-1];

// last index of the array is assigned the original first element of the array copied in temp

a[k-1]=temp;

cout<<endl<<"The elements of the array after swapping are"<<endl;

for(l=0; l<k; l++)

{

cout<<a[l]<<"\t";

}

}

User Deepak A
by
8.5k points