fork download
  1. //Diego Martinez CSC5 Chapter 9, P.537,#10
  2. /*******************************************************************************
  3. * REVERSING AN INTEGER ARRAY USING DYNAMIC MEMORY ALLOCATION
  4. * ______________________________________________________________________________
  5. * This program creates a dynamically allocated copy of an integer array in
  6. * reverse order using a function that returns a pointer to the new array.
  7. * The program then displays both the original array and the reversed copy.
  8. *
  9. * Computation is based on the Formula:
  10. *
  11. * newArray[i] = arr[size - 1 - i]
  12. *
  13. *______________________________________________________________________________
  14. * INPUT
  15. *
  16. * original integer array values
  17. * size of the array
  18. *
  19. * OUTPUT
  20. *
  21. * display of the original array
  22. * display of the reversed array copy
  23. *
  24. *******************************************************************************/
  25. #include <iostream>
  26. using namespace std;
  27.  
  28. // Function prototype
  29. int* reverseArray(int arr[], int size);
  30.  
  31. int main()
  32. {
  33. // Original array
  34. int numbers[] = {10, 20, 30, 40, 50};
  35.  
  36. int size = 5;
  37.  
  38. // Call function and store returned pointer
  39. int* reversed = reverseArray(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 reversed copy
  51. cout << "Reversed Copy: ";
  52. for (int i = 0; i < size; i++)
  53. {
  54. cout << reversed[i] << " ";
  55. }
  56.  
  57. cout << endl;
  58.  
  59. // Free dynamically allocated memory
  60. delete[] reversed;
  61.  
  62. return 0;
  63. }
  64.  
  65. // Function definition
  66. int* reverseArray(int arr[], int size)
  67. {
  68. // Dynamically allocate new array
  69. int* newArray = new int[size];
  70.  
  71. // Copy elements in reverse order
  72. for (int i = 0; i < size; i++)
  73. {
  74. newArray[i] = arr[size - 1 - i];
  75. }
  76.  
  77. // Return pointer to new array
  78. return newArray;
  79. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Original Array: 10 20 30 40 50 
Reversed Copy: 50 40 30 20 10