// Sam Partovi CS1A Ch. 9, P. 539, #10
//
/*******************************************************************************
* CREATE REVERSED ARRAY
* ____________________________________________________________
* This program accepts an integer array and its size, creates a new array
* that contains all contents in reverse order, and copies the contents of the
* original array into the new array.
* ____________________________________________________________
* INPUT
* origArray: The original integer array
* arraySize: The size of the array
* OUTPUT
* newArray: Pointer to the new array with reversed elements
*******************************************************************************/
#include <iostream>
using namespace std;
//Function prototype
int* createReversedArray(const int origArray[], int arraySize);
int main() {
const int arraySize = 5; //INPUT - Size of the array
int origArray[arraySize] = {1, 2, 3, 4, 5}; //INPUT - Original array
//Create and initialize a new reversed array
int* newArray = createReversedArray(origArray, arraySize);
//Display the contents of the new array
cout << "Reversed array: ";
for (int i = 0; i < arraySize; i++) {
cout << newArray[i] << " ";
}
cout << endl;
//Free allocated memory
delete[] newArray;
return 0;
}
// *****************************************************************************
// Function definition for createReversedArray: *
// This function creates a new array that contains the elements of the *
// original array in reverse order. *
// *****************************************************************************
int* createReversedArray(const int origArray[], int arraySize) {
//Dynamically allocate memory for the new array
int* newArray = new int[arraySize];
//Copy elements from the original array in reverse order
for (int i = 0; i < arraySize; i++) {
newArray[i] = origArray[arraySize - 1 - i];
}
return newArray;
}