fork download
  1. // Sam Partovi CS1A Ch. 9, P. 539, #11
  2. //
  3. /*******************************************************************************
  4. * CREATE AND INITIALIZE NEW ARRAY
  5. * ____________________________________________________________
  6. * This program accepts an integer array and its size, creates a new array
  7. * that is twice the size of the input array, copies the contents of the
  8. * original array into the new array, and initializes the remaining elements
  9. * of the new array with 0.
  10. * ____________________________________________________________
  11. * INPUT
  12. * origArray: The original integer array
  13. * origSize: The size of the original array
  14. * OUTPUT
  15. * newArray: Pointer to the new array with copied and initialized elements
  16. *******************************************************************************/
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. //Function prototype
  21. int* createAndInitializeArray(const int origArray[], int origSize);
  22.  
  23. int main() {
  24. const int origSize = 5; // INPUT - Size of the original array
  25. int origArray[origSize] = {1, 2, 3, 4, 5}; // INPUT - Original array
  26.  
  27. //Create and initialize a new array
  28. int* newArray = createAndInitializeArray(origArray, origSize);
  29.  
  30. //Display the contents of the new array
  31. cout << "New array: ";
  32. for (int i = 0; i < origSize * 2; i++) {
  33. cout << newArray[i] << " ";
  34. }
  35. cout << endl;
  36.  
  37. //Free allocated memory
  38. delete[] newArray;
  39.  
  40. return 0;
  41. }
  42.  
  43. // *****************************************************************************
  44. // Function definition for createAndInitializeArray: *
  45. // This function creates a new array with double the size of the original *
  46. // array, copies the original array elements into it, and initializes the *
  47. // remaining elements to 0. *
  48. // *****************************************************************************
  49. int* createAndInitializeArray(const int origArray[], int origSize) {
  50. //Allocate memory for the new array
  51. int* newArray = new int[origSize * 2];
  52.  
  53. //Copy elements from the original array
  54. for (int i = 0; i < origSize; i++) {
  55. newArray[i] = origArray[i];
  56. }
  57.  
  58. //Initialize remaining elements to 0
  59. for (int i = origSize; i < origSize * 2; i++) {
  60. newArray[i] = 0;
  61. }
  62.  
  63. return newArray;
  64. }
  65.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
New array: 1 2 3 4 5 0 0 0 0 0