fork download
  1. //Cameron Pham CS1A Chapter 9, p. 539, #11
  2. //
  3. /******************************************************************************
  4. * EXPAND ARRAY
  5. * ______________________________________________________________________________
  6. * This program uses a function to dynamically create a new integer array that is
  7. * twice the size of an original array. The function copies the original array's
  8. * elements into the new array and initializes the remaining elements to zero.
  9. * It then returns a pointer to the expanded array.
  10. *******************************************************************************/
  11. #include <iostream>
  12. using namespace std;
  13.  
  14. // Function prototype
  15. int* expandArray(int* numbers, int size);
  16. int main()
  17. {
  18. const int SIZE = 5;
  19. int numbers[SIZE] = {10, 20, 30, 40, 50};
  20. int* expandedArray;
  21. // Expand the original array
  22. expandedArray = expandArray(numbers, SIZE);
  23. // Display the original array
  24. cout << "Original array:" << endl;
  25. for (int count = 0; count < SIZE; count++)
  26. {
  27. cout << *(numbers + count) << " ";
  28. }
  29. // Display the expanded array
  30. cout << "\n\nExpanded array:" << endl;
  31. for (int count = 0; count < SIZE * 2; count++)
  32. {
  33. cout << *(expandedArray + count) << " ";
  34. }
  35. cout << endl;
  36. // Release dynamically allocated memory
  37. delete[] expandedArray;
  38. expandedArray = nullptr;
  39. return 0;
  40. }
  41. // Create and return an array twice the original size
  42. int* expandArray(int* numbers, int size)
  43. {
  44. int* newArray = new int[size * 2];
  45. // Copy the original elements
  46. for (int count = 0; count < size; count++)
  47. {
  48. *(newArray + count) = *(numbers + count);
  49. }
  50. // Initialize the remaining elements to zero
  51. for (int count = size; count < size * 2; count++)
  52. {
  53. *(newArray + count) = 0;
  54. }
  55. return newArray;
  56. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Original array:
10 20 30 40 50 

Expanded array:
10 20 30 40 50 0 0 0 0 0