//Diego Martinez CSC5 Chapter 9, P.539,#12
/*******************************************************************************
* Shifting Integer Array Elements Using Dynamic Memory Allocation
* ______________________________________________________________________________
* This program creates a new dynamically allocated array that is one element
* larger than the original integer array. The program sets the first element
* of the new array to 0 and shifts all original array elements one position
* to the right.
*
* Computation is based on the Formula:
*
* newArray[i + 1] = arr[i]
*
*______________________________________________________________________________
* INPUT
*
* original integer array values
* size of the original array
*
* OUTPUT
*
* display of the original array
* display of the shifted array with leading 0
*
*******************************************************************************/
#include <iostream>
using namespace std;
// Function prototype
int* shiftArray(int arr[], int size);
int main()
{
// Original array
int numbers[] = {10, 20, 30, 40, 50};
int size = 5;
// Call function and store returned pointer
int* shifted = shiftArray(numbers, size);
// Display original array
cout << "Original Array: ";
for (int i = 0; i < size; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
// Display shifted array
cout << "Shifted Array: ";
for (int i = 0; i < size + 1; i++)
{
cout << shifted[i] << " ";
}
cout << endl;
// Free dynamically allocated memory
delete[] shifted;
return 0;
}
// Function definition
int* shiftArray(int arr[], int size)
{
// Create new array one element larger
int* newArray = new int[size + 1];
// Set first element to 0
newArray[0] = 0;
// Copy original array elements shifted by one position
for (int i = 0; i < size; i++)
{
newArray[i + 1] = arr[i];
}
// Return pointer to new array
return newArray;
}