11-Array Expander: Write a function that accepts an int array and the array s si
ID: 3546797 • Letter: 1
Question
11-Array Expander:
Write a function that accepts an int array and the array s size as arguments. The
function should create a new array that is twice the size of the argument array. The
function should copy the contents of the argument array to the new array, and initialize
the unused elements of the second array with 0. The function should return a
pointer to the new array.
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 rst 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.
I need the code in C++ please.
Explanation / Answer
// PROGRAM 1 SOLUTION
#include<iostream>
using namespace std;
int* array_expander(int array[],int size)
{
int* pointer_to_new_array = new int[2*size];
for(int i=0; i<2*size; i++)
{
if(i<size)
pointer_to_new_array[i] = array[i];
else
pointer_to_new_array[i]= 0;
}
return pointer_to_new_array;
}
int main()
{
int array[]={1,2,3,4,5};
int *new_array = array_expander(array,5);
cout <<"new array contents are ";
for(int i=0; i<10; i++)
cout << new_array[i] << " " ;
cout << endl;
return 0;
}
// PROGRAM 2 SOLUTION
#include<iostream>
using namespace std;
int* element_shifter(int array[],int size)
{
int* pointer_to_new_array = new int[size+1];
pointer_to_new_array[0]=0;
for(int i=1; i<=size; i++)
{
pointer_to_new_array[i] = array[i-1];
}
return pointer_to_new_array;
}
int main()
{
int array[]={1,2,3,4,5};
int *new_array = element_shifter(array,5);
cout <<"new array contents are ";
for(int i=0; i<6; i++)
cout << new_array[i] << " " ;
cout << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.