The language is C++. Thank you. Element Shifter Write a function that accepts an
ID: 3855558 • Letter: T
Question
The language is C++. Thank you.
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.Explanation / Answer
Here is the code for you:
#include<iostream>
#include <fstream>
using namespace std;
int* elementShifter(int *array, int size)
{
//Create a new array one element larger than argument array.
int *newArray = new int[size+1];
//The first element of the new array should be set to 0.
*(newArray) = 0;
//Element 0 of the argument array should be copied to element 1 of new array,
//and so on...
for(int i = 0; i < size; i++)
*(newArray + i + 1) = *(array + i);
return newArray;
}
int main()
{
ifstream fin;
int size;
//cout<<"Enter a value not more than 50: ";
cin>>size;
int *array = new int[size];
if(size > 0 && size <= 50)
{
//Read N integers from the file named data into an array.
for(int i = 0; i < size; i++)
fin>> *(array+i);
//Passes the array to element shifter.
array = elementShifter(array, size);
for(int i = 0; i < size+1; i++)
cout<<*(array+i)<<endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.