fork download
  1. // Timothy Price CS1A Ch 9 Challenge 11
  2. /******************************************************************************
  3.  * Increase array size
  4.  *
  5.  * This program receives an array, copies its values to a new array and doubles
  6.  * its size with dynamic allocation.
  7.  *
  8.  * Input:
  9.  * base array
  10.  *
  11.  * Output:
  12.  * new array
  13.  *****************************************************************************/
  14.  
  15. #include <iostream>
  16.  
  17. using namespace std;
  18.  
  19. // Function Prototype
  20. int* doubleSizeAndCopy(const int arr[], int size);
  21. void printArray(const int arr[], int size);
  22.  
  23. int main() {
  24. const int SIZE = 5;
  25. int original[SIZE] = {4, 8, 15, 16, 23};
  26.  
  27. int* expanded = doubleSizeAndCopy(original, SIZE);
  28.  
  29. cout << "Original array (size " << SIZE << "): ";
  30. printArray(original, SIZE);
  31.  
  32. if (expanded != nullptr) {
  33. cout << "Expanded array (size " << SIZE * 2 << "): ";
  34. printArray(expanded, SIZE * 2);
  35.  
  36. // Release dynamically allocated memory
  37. delete[] expanded;
  38. expanded = nullptr;
  39. }
  40.  
  41. return 0;
  42. }
  43.  
  44. // Allocates a new array of size * 2, copies arr, and fills remaining elements with 0
  45. int* doubleSizeAndCopy(const int arr[], int size) {
  46. if (arr == nullptr || size <= 0) {
  47. return nullptr;
  48. }
  49.  
  50. int newSize = size * 2;
  51. int* newArr = new int[newSize];
  52.  
  53. for (int i = 0; i < size; ++i) {
  54. newArr[i] = arr[i];
  55. }
  56.  
  57. for (int i = size; i < newSize; ++i) {
  58. newArr[i] = 0;
  59. }
  60.  
  61. return newArr;
  62. }
  63.  
  64. // Helper function to print array elements
  65. void printArray(const int arr[], int size) {
  66. for (int i = 0; i < size; ++i) {
  67. cout << arr[i] << " ";
  68. }
  69. cout << endl;
  70. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Original array (size 5): 4 8 15 16 23 
Expanded array (size 10): 4 8 15 16 23 0 0 0 0 0