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