1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
//This Program will create a new array
//that will be twice the size of the original.
# include <iostream>
using namespace std;
//Function prototypes
void displayArray(const int [], int); //displays original array and expanded array
int *duplicateArray(const int * , int); //duplicates original array and doubles amount of elements
/***************
Main function
***************/
int main ()
{
const int SIZE = 10;
int array[SIZE] = {10, 20, 30, 40, 50, //orignal Array holds 10 elements
60, 70, 80, 90, 100,};
int *dupArray; //defines the pointer to duplicated array
dupArray = duplicateArray(array, SIZE);
//displays original array
cout<< "Here are the original array's elements:\n ";
displayArray(array, SIZE);
//displays duplicated array with double the elements
cout << "Here is the new duplicated array with double ";
cout << "The amount of elements.\n :";
displayArray(dupArray, (SIZE *2));
delete [] dupArray; //frees allocated memory and sets dupArray to zero
dupArray = 0;
cout <<" Press [Enter] to continue..."
//ignores 10000 chars in keyboard buffer
cin.ignore(10000, '\n');
//program closes after user presses enter
cin.get();
return 0;
}
/*********************************************************
duplicateArray function doubles the size of the
original array and places a zero in the empty elements
*********************************************************/
int *duplicateArray (const int *arr, int size)
{
//Creates dynamic allocated memory space for array newArray
int *newArray = new int [(size * 2)];
//Validates that newArray's size will return null if
//zero or a negative was passed
if ((size *2) <= 0)
return NULL;
//duplicates the contents of the original array into newArray
for (int dupElem = 0; dupElem < (size); dupElem++)
{
newArray[dupElem] = arr[size];
while (newArray[10] < newArray[19]) //new elements are assigned zero
newArray[dupElem] = 0;
}
//Returns pointer to the new array
return newArray;
}
/*******************************************
Function displayArray displays original and
duplicated array elements
********************************************/
void displayArray (const int arr [], int size)
{
for (int index = 0; index < size; index++)
cout << arr[index] << " ";
cout << endl;
}
| |