//Cameron Pham CS1A Chapter 9, p. 539, #11
//
/******************************************************************************
* EXPAND ARRAY
* ______________________________________________________________________________
* This program uses a function to dynamically create a new integer array that is
* twice the size of an original array. The function copies the original array's
* elements into the new array and initializes the remaining elements to zero.
* It then returns a pointer to the expanded array.
*******************************************************************************/
#include <iostream>
using namespace std;
// Function prototype
int* expandArray(int* numbers, int size);
int main()
{
const int SIZE = 5;
int numbers[SIZE] = {10, 20, 30, 40, 50};
int* expandedArray;
// Expand the original array
expandedArray = expandArray(numbers, SIZE);
// Display the original array
cout << "Original array:" << endl;
for (int count = 0; count < SIZE; count++)
{
cout << *(numbers + count) << " ";
}
// Display the expanded array
cout << "\n\nExpanded array:" << endl;
for (int count = 0; count < SIZE * 2; count++)
{
cout << *(expandedArray + count) << " ";
}
cout << endl;
// Release dynamically allocated memory
delete[] expandedArray;
expandedArray = nullptr;
return 0;
}
// Create and return an array twice the original size
int* expandArray(int* numbers, int size)
{
int* newArray = new int[size * 2];
// Copy the original elements
for (int count = 0; count < size; count++)
{
*(newArray + count) = *(numbers + count);
}
// Initialize the remaining elements to zero
for (int count = size; count < size * 2; count++)
{
*(newArray + count) = 0;
}
return newArray;
}