Answer to Question #260524 in C++ for malika

Question #260524

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}.


#include <iostream>

using namespace std;


/* Your solution goes here */


int main() {

  const int SORT_ARR_SIZE = 4;

  int sortArray[SORT_ARR_SIZE];

  int i;

  int userNum;


  for (i = 0; i < SORT_ARR_SIZE; ++i) {

   cin >> userNum;

   sortArray[i] = userNum;

  }


  SwapArrayEnds(sortArray, SORT_ARR_SIZE);


  for (i = 0; i < SORT_ARR_SIZE; ++i) {

   cout << sortArray[i] << " ";

  }

  cout << endl;


  return 0;

}


1
Expert's answer
2021-11-08T17:37:36-0500
using namespace std;


void SwapArrayEnds(int *arr, int n)
{
	int x;
	x = *(arr+n-1);
	*(arr+n-1) = *(arr+0);
	*(arr+0) = x;
}


int main() 
{
	const int SORT_ARR_SIZE = 4;
	int sortArray[SORT_ARR_SIZE];
	int i;
	int userNum;


	for (i = 0; i < SORT_ARR_SIZE; ++i) 
	{
		cin >> userNum;
	   	sortArray[i] = userNum;
	}
	
	SwapArrayEnds(&sortArray[0], SORT_ARR_SIZE);
	for (i = 0; i < SORT_ARR_SIZE; ++i) 
	{
		cout << sortArray[i] << " ";
	}
	cout << endl;
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS