// Torrez, Elaine CS1A Chapter 9, P. 539, #11
/********************************************************************************************
*
* ARRAY EXPANDER
*
* ------------------------------------------------------------------------------------------
* This program demonstrates a function that accepts an integer pointer and its size, and
* returns a NEW dynamically allocated array that is twice as large. The original array's
* values are copied into the new array, and the remaining elements are initialized to 0.
*
* ------------------------------------------------------------------------------------------
* INPUT
* size : Number of integers
* arr : Original integers entered by the user
*
* OUTPUT
* Expanded array containing original values followed by zeros
*
********************************************************************************************/
#include <iostream>
using namespace std;
// FUNCTION PROTOTYPE
int *expandArray(int *arr, int size);
int main()
{
int size;
int *arr = nullptr;
int *expanded = nullptr;
// INPUT
cout << "Enter number of integers: ";
cin >> size;
while (size <= 0)
{
cout << "Error: Enter a number greater than 0: ";
cin >> size;
}
arr = new int[size];
for (int i = 0; i < size; i++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> arr[i];
}
// Expand the array
expanded = expandArray(arr, size);
// OUTPUT
cout << "\nExpanded Array (size = " << size * 2 << "):\n";
for (int i = 0; i < size * 2; i++)
{
cout << "Element [" << i << "] = " << expanded[i] << endl;
}
delete [] arr;
delete [] expanded;
arr = nullptr;
expanded = nullptr;
return 0;
}
//*******************************************************************************
// expandArray
//------------------------------------------------------------------------------
// Creates a new array twice the size of the original.
// Copies original values and fills remaining spots with 0.
//*******************************************************************************
int *expandArray(int *arr, int size)
{
int newSize = size * 2;
int *newArr = new int[newSize];
for (int i = 0; i < size; i++)
newArr[i] = arr[i];
for (int i = size; i < newSize; i++)
newArr[i] = 0;
return newArr;
}