fork download
  1. /******************************************************************************
  2.  * Reorder array contents
  3.  *
  4.  * This Program receives an set of values and stores them within an array, then
  5.  * reverses the order of the values within a new array.
  6.  *
  7.  * Input:
  8.  * array
  9.  *
  10.  * Output:
  11.  * reversed array
  12.  *****************************************************************************/
  13.  
  14. #include <iostream>
  15.  
  16. using namespace std;
  17.  
  18. // Function Prototype
  19. int* reverseCopy(const int arr[], int size);
  20. void printArray(const int arr[], int size);
  21.  
  22. int main() {
  23. const int SIZE = 7;
  24. int original[SIZE] = {10, 20, 30, 40, 50, 60, 70};
  25.  
  26. int* reversed = reverseCopy(original, SIZE);
  27.  
  28. cout << "Original array: ";
  29. printArray(original, SIZE);
  30.  
  31. if (reversed != nullptr) {
  32. cout << "Reversed copy: ";
  33. printArray(reversed, SIZE);
  34.  
  35. // Clean up dynamically allocated memory
  36. delete[] reversed;
  37. reversed = nullptr;
  38. }
  39.  
  40. return 0;
  41. }
  42.  
  43. // Dynamically allocates a new array in reverse order
  44. int* reverseCopy(const int arr[], int size) {
  45. if (arr == nullptr || size <= 0) {
  46. return nullptr;
  47. }
  48.  
  49. int* copy = new int[size];
  50. for (int i = 0; i < size; ++i) {
  51. copy[i] = arr[size - 1 - i];
  52. }
  53.  
  54. return copy;
  55. }
  56.  
  57. // Helper function to display array elements
  58. void printArray(const int arr[], int size) {
  59. for (int i = 0; i < size; ++i) {
  60. cout << arr[i] << " ";
  61. }
  62. cout << endl;
  63. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Original array: 10 20 30 40 50 60 70 
Reversed copy:  70 60 50 40 30 20 10