fork download
  1. //Charlotte Davies-Kiernan CS1A Chapter 9 P.539 #12
  2. //
  3. /******************************************************************************
  4.  *
  5.  * Compute Element Shifter
  6.  * ____________________________________________________________________________
  7.  * This program will accept an array that is inputted by the user and then
  8.  * display a new array that is led by zero as the first element and the
  9.  * remaining elements will be shifted over one from the original array.
  10.  * ____________________________________________________________________________
  11.  * Input
  12.  * size :amount of elements user decides
  13.  * arr :integers that make up the array chosen by user
  14.  * Output
  15.  * newArr :new array leading with 0
  16.  *****************************************************************************/
  17. #include <iostream>
  18. #include <iomanip>
  19. using namespace std;
  20.  
  21. //Function Prototype
  22. int* addLeadingZero(int* arr, int size);
  23.  
  24. int main() {
  25. //Data Dictionary
  26. int size;
  27. int* arr;
  28. int* newArr;
  29.  
  30. //User Input
  31. cout << "Enter the size of the array: " << endl;
  32. cin >> size;
  33.  
  34. arr = new int[size];
  35. cout << "Enter " << size << " integers: " << endl;
  36. for(int i = 0; i < size; i++){
  37. cin >> arr[i];
  38. }
  39.  
  40. //Invoke Function
  41. newArr = addLeadingZero(arr, size);
  42.  
  43. //Display New Array
  44. cout << "New array (1 element larger, starting with 0): " << endl;
  45. for(int i = 0; i < size + 1; i++){
  46. cout << newArr[i] << " ";
  47. }
  48. //Free Memory
  49. delete[] arr;
  50. delete[] newArr;
  51.  
  52. return 0;
  53. }
  54.  
  55. //Function Definition
  56. int* addLeadingZero(int* arr, int size){
  57. int* newArr = new int[size];
  58. newArr[0] = 0;
  59. for(int i = 0; i < size; i++){
  60. newArr[i + 1] = arr[i];
  61. }
  62. return newArr;
  63. }
Success #stdin #stdout 0s 5300KB
stdin
5
1
2
3
4
5
stdout
Enter the size of the array: 
Enter 5 integers: 
New array (1 element larger, starting with 0): 
0 1 2 3 4 5