fork download
  1. //Diego Martinez CSC5 Chapter 9, P.537,#11
  2. /*******************************************************************************
  3. * Expanding an Integer Array Using Dynamic Memory Allocation
  4. * ______________________________________________________________________________
  5. * This program creates a new dynamically allocated array that is twice the
  6. * size of the original integer array. The program copies the original array
  7. * values into the new array and initializes the remaining elements with 0.
  8. *
  9. * Computation is based on the Formula:
  10. *
  11. * new size = size * 2
  12. *
  13. *______________________________________________________________________________
  14. * INPUT
  15. *
  16. * original integer array values
  17. * size of the original array
  18. *
  19. * OUTPUT
  20. *
  21. * display of the original array
  22. * display of the expanded array with added zeros
  23. *
  24. *******************************************************************************/
  25. #include <iostream>
  26. using namespace std;
  27.  
  28. // Function prototype
  29. int* expandArray(int arr[], int size);
  30.  
  31. int main()
  32. {
  33. // Original array
  34. int numbers[] = {5, 10, 15, 20, 25};
  35.  
  36. int size = 5;
  37.  
  38. // Call function and store returned pointer
  39. int* expanded = expandArray(numbers, size);
  40.  
  41. // Display original array
  42. cout << "Original Array: ";
  43. for (int i = 0; i < size; i++)
  44. {
  45. cout << numbers[i] << " ";
  46. }
  47.  
  48. cout << endl;
  49.  
  50. // Display expanded array
  51. cout << "Expanded Array: ";
  52. for (int i = 0; i < size * 2; i++)
  53. {
  54. cout << expanded[i] << " ";
  55. }
  56.  
  57. cout << endl;
  58.  
  59. // Free dynamically allocated memory
  60. delete[] expanded;
  61.  
  62. return 0;
  63. }
  64.  
  65. // Function definition
  66. int* expandArray(int arr[], int size)
  67. {
  68. // Create new array twice the size
  69. int* newArray = new int[size * 2];
  70.  
  71. // Copy original array values
  72. for (int i = 0; i < size; i++)
  73. {
  74. newArray[i] = arr[i];
  75. }
  76.  
  77. // Initialize remaining elements with 0
  78. for (int i = size; i < size * 2; i++)
  79. {
  80. newArray[i] = 0;
  81. }
  82.  
  83. // Return pointer to new array
  84. return newArray;
  85. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Original Array: 5 10 15 20 25 
Expanded Array: 5 10 15 20 25 0 0 0 0 0