fork download
  1. //Maxwell Brewer CS1A Chapter 9, p. 539, #11
  2. //
  3. /*******************************************************************************
  4.  * ARRAY EXPANDER
  5.  * _____________________________________________________________________________
  6.  * This program will dynamically allocate an array of a specified size.
  7.  * _____________________________________________________________________________
  8.  * INPUT
  9.  * No direct input from the user
  10.  *
  11.  * OUTPUT
  12.  * Prints the original and expanded arrays,
  13.  * showing the original values followed by zero-initialized elements.
  14.  *
  15.  ******************************************************************************/
  16.  
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. int* expandArray(int *arr, int SIZE) {
  21. // Dynamically allocate an array twice the size
  22. int *expPtr = new int[2 * SIZE];
  23.  
  24. // Initialize elements of new array
  25. for (int i = 0; i < 2 * SIZE; i++) {
  26. if (i < SIZE) {
  27.  
  28. // Copy elements of the original array
  29. *(expPtr + i) = *(arr + i);
  30. } else {
  31.  
  32. // Initialize additional elements to 0
  33. *(expPtr + i) = 0;
  34. }
  35. }
  36.  
  37. return expPtr;
  38. }
  39.  
  40. int main() {
  41. int SIZE = 5;
  42. int *arr = new int[SIZE]{1, 2, 3, 4, 5};
  43.  
  44. // Print original array
  45. cout << "Original array: ";
  46. for (int i = 0; i < SIZE; i++) {
  47. cout << arr[i] << " ";
  48. }
  49. cout << endl;
  50.  
  51. // Expand the array
  52. int *expandedArr = expandArray(arr, SIZE);
  53.  
  54. // Print expanded array
  55. cout << "Expanded array: ";
  56. for (int i = 0; i < 2 * SIZE; i++) {
  57. cout << expandedArr[i] << " ";
  58. }
  59. cout << endl;
  60.  
  61. // Free memory
  62. delete[] arr;
  63. delete[] expandedArr;
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Standard output is empty