fork download
  1. //Ryan Shahriyarpour CS1A Chapter 9 Question 10
  2. /*****************************************************************************
  3.  *
  4.  * Reverse an Array
  5.  *
  6.  *********************
  7.  *
  8.  * This program makes a copy of an array with the elements in reverse order.
  9.  * It displays the original array and the reversed copy.
  10.  *
  11.  * INPUT
  12.  * None (the array is set in the program)
  13.  *
  14.  * OUTPUT
  15.  * The original array and the reversed copy
  16.  *
  17.  ****************************************************************************/
  18.  
  19. #include <iostream>
  20. using namespace std;
  21.  
  22. const int SIZE = 6; // Number of elements in the array
  23.  
  24. // Function prototypes
  25. int *reverseArray(const int *array, int size);
  26. void showArray(const int *array, int size);
  27.  
  28. int main()
  29. {
  30. // data dictionary
  31. int original[SIZE] = {10, 20, 30, 40, 50, 60}; // The original array
  32. int *reversed; // Pointer to the reversed copy
  33.  
  34. reversed = reverseArray(original, SIZE);
  35.  
  36. cout << "Original array: ";
  37. showArray(original, SIZE);
  38. cout << "Reversed copy: ";
  39. showArray(reversed, SIZE);
  40.  
  41. // Free the memory
  42. delete [] reversed;
  43. reversed = nullptr;
  44.  
  45. return 0;
  46. }
  47.  
  48. // Returns a pointer to a new array holding the elements in reverse order
  49. int *reverseArray(const int *array, int size)
  50. {
  51. int *newArray = new int[size]; // Pointer to the new array
  52. int count; // Loop counter
  53.  
  54. for (count = 0; count < size; count++)
  55. *(newArray + count) = *(array + (size - 1 - count));
  56.  
  57. return newArray;
  58. }
  59.  
  60. // Displays the elements of an array on one line
  61. void showArray(const int *array, int size)
  62. {
  63. int count; // Loop counter
  64.  
  65. for (count = 0; count < size; count++)
  66. cout << *(array + count) << " ";
  67. cout << endl;
  68. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Original array: 10 20 30 40 50 60 
Reversed copy:  60 50 40 30 20 10