fork download
  1. //Diego Martinez CSC5 Chapter 9, P.539,#12
  2. /*******************************************************************************
  3. * Shifting Integer Array Elements Using Dynamic Memory Allocation
  4. * ______________________________________________________________________________
  5. * This program creates a new dynamically allocated array that is one element
  6. * larger than the original integer array. The program sets the first element
  7. * of the new array to 0 and shifts all original array elements one position
  8. * to the right.
  9. *
  10. * Computation is based on the Formula:
  11. *
  12. * newArray[i + 1] = arr[i]
  13. *
  14. *______________________________________________________________________________
  15. * INPUT
  16. *
  17. * original integer array values
  18. * size of the original array
  19. *
  20. * OUTPUT
  21. *
  22. * display of the original array
  23. * display of the shifted array with leading 0
  24. *
  25. *******************************************************************************/
  26. #include <iostream>
  27. using namespace std;
  28.  
  29. // Function prototype
  30. int* shiftArray(int arr[], int size);
  31.  
  32. int main()
  33. {
  34. // Original array
  35. int numbers[] = {10, 20, 30, 40, 50};
  36.  
  37. int size = 5;
  38.  
  39. // Call function and store returned pointer
  40. int* shifted = shiftArray(numbers, size);
  41.  
  42. // Display original array
  43. cout << "Original Array: ";
  44. for (int i = 0; i < size; i++)
  45. {
  46. cout << numbers[i] << " ";
  47. }
  48.  
  49. cout << endl;
  50.  
  51. // Display shifted array
  52. cout << "Shifted Array: ";
  53. for (int i = 0; i < size + 1; i++)
  54. {
  55. cout << shifted[i] << " ";
  56. }
  57.  
  58. cout << endl;
  59.  
  60. // Free dynamically allocated memory
  61. delete[] shifted;
  62.  
  63. return 0;
  64. }
  65.  
  66. // Function definition
  67. int* shiftArray(int arr[], int size)
  68. {
  69. // Create new array one element larger
  70. int* newArray = new int[size + 1];
  71.  
  72. // Set first element to 0
  73. newArray[0] = 0;
  74.  
  75. // Copy original array elements shifted by one position
  76. for (int i = 0; i < size; i++)
  77. {
  78. newArray[i + 1] = arr[i];
  79. }
  80.  
  81. // Return pointer to new array
  82. return newArray;
  83. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Original Array: 10 20 30 40 50 
Shifted Array: 0 10 20 30 40 50