// Sam Partovi CS1A Ch. 9, P. 539, #11
//
/*******************************************************************************
* CREATE AND INITIALIZE NEW ARRAY
* ____________________________________________________________
* This program accepts an integer array and its size, creates a new array
* that is twice the size of the input array, copies the contents of the
* original array into the new array, and initializes the remaining elements
* of the new array with 0.
* ____________________________________________________________
* INPUT
* origArray: The original integer array
* origSize: The size of the original array
* OUTPUT
* newArray: Pointer to the new array with copied and initialized elements
*******************************************************************************/
#include <iostream>
using namespace std;
//Function prototype
int* createAndInitializeArray(const int origArray[], int origSize);
int main() {
const int origSize = 5; // INPUT - Size of the original array
int origArray[origSize] = {1, 2, 3, 4, 5}; // INPUT - Original array
//Create and initialize a new array
int* newArray = createAndInitializeArray(origArray, origSize);
//Display the contents of the new array
cout << "New array: ";
for (int i = 0; i < origSize * 2; i++) {
cout << newArray[i] << " ";
}
cout << endl;
//Free allocated memory
delete[] newArray;
return 0;
}
// *****************************************************************************
// Function definition for createAndInitializeArray: *
// This function creates a new array with double the size of the original *
// array, copies the original array elements into it, and initializes the *
// remaining elements to 0. *
// *****************************************************************************
int* createAndInitializeArray(const int origArray[], int origSize) {
//Allocate memory for the new array
int* newArray = new int[origSize * 2];
//Copy elements from the original array
for (int i = 0; i < origSize; i++) {
newArray[i] = origArray[i];
}
//Initialize remaining elements to 0
for (int i = origSize; i < origSize * 2; i++) {
newArray[i] = 0;
}
return newArray;
}