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