In: Computer Science
C++
9.12: Element Shifter Write a function that accepts an int array and the array’s size as arguments. The function should create a new array that is one element larger than the argument array. The first element of the new array should be set to 0. Element 0 of the argument array should be copied to element 1 of the new array, element 1 of the argument array should be copied to element 2 of the new array, and so forth. The function should return a pointer to the new array. Demonstrate the function by using it in a main program that reads an integer N (that is not more than 50) from standard input and then reads N integers from a file named data into an array. The program then passes the array to your element shifter function, and prints the values of the new expanded and shifted array on standard output, one value per line. You may assume that the file data has at least N values. Prompts And Output Labels. There are no prompts for the integer and no labels for the reversed array that is printed out. Input Validation. If the integer read in from standard input exceeds 50 or is less than 0 the program terminates silently.
Code:
#include <iostream> #include <fstream> using namespace std; // function to shift the array provided size and array int *element_shifter(int arr[], int size) { // declare a new array of size+1 int *shifted_arr = new int[size+1]; // make first element to 0 shifted_arr[0] = 0; // copy rest of the array to new array for(int i = 1; i <= size; i++) { shifted_arr[i] = arr[i-1]; } // return pointer to new array created return shifted_arr; } // main or driver fuction int main() { // read value for n or size of array int n; cin >> n; // validate input for n if(n > 50 || n < 1) { return -1; } // open file in read mode fstream f; f.open("data.txt", ios::in); int arr[n]; int i = 0, x; // read data file and store first n elements in array while(f >> x) { arr[i] = x; if(i == n-1) { break; } i++; } // call function to shiFt array and store pointer in a int * variable int *shifted = element_shifter(arr, n); cout << endl; // display the shifted array for(int i = 0; i < n+1; i++) { cout << *(shifted + i) << endl; } }
Text file:
data.txt:
10
2
3
4
1
13
12
223
4
5
9
0
12
4
5
6
7
4
5
6
90
7
6
5
6
1
12
2
32
1
2
232
43
434
33
2
21
12
3
34
35
54
5
6
5
7
78
79
89
89
Output:
FOR HELP PLEASE COMMENT.
THANK YOU