//Diego Martinez CSC5 Chapter 9, P.537,#11
/*******************************************************************************
* Expanding an Integer Array Using Dynamic Memory Allocation
* ______________________________________________________________________________
* This program creates a new dynamically allocated array that is twice the
* size of the original integer array. The program copies the original array
* values into the new array and initializes the remaining elements with 0.
*
* Computation is based on the Formula:
*
* new size = size * 2
*
*______________________________________________________________________________
* INPUT
*
* original integer array values
* size of the original array
*
* OUTPUT
*
* display of the original array
* display of the expanded array with added zeros
*
*******************************************************************************/
#include <iostream>
using namespace std;
// Function prototype
int* expandArray(int arr[], int size);
int main()
{
// Original array
int numbers[] = {5, 10, 15, 20, 25};
int size = 5;
// Call function and store returned pointer
int* expanded = expandArray(numbers, size);
// Display original array
cout << "Original Array: ";
for (int i = 0; i < size; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
// Display expanded array
cout << "Expanded Array: ";
for (int i = 0; i < size * 2; i++)
{
cout << expanded[i] << " ";
}
cout << endl;
// Free dynamically allocated memory
delete[] expanded;
return 0;
}
// Function definition
int* expandArray(int arr[], int size)
{
// Create new array twice the size
int* newArray = new int[size * 2];
// Copy original array values
for (int i = 0; i < size; i++)
{
newArray[i] = arr[i];
}
// Initialize remaining elements with 0
for (int i = size; i < size * 2; i++)
{
newArray[i] = 0;
}
// Return pointer to new array
return newArray;
}