in C++ and with comments please Write a function that accepts an int array and t
ID: 3875982 • Letter: I
Question
in C++ and with comments please
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 that it works with at least two different sized arrays. SHOW me your working program, and also copy/paste your code and output to a word doc and submit (no lab report needed)
Explanation / Answer
#include <iostream>
using namespace std;
int* copyArray(int arr1[],const int n) {
int *arr2 = new int[n+1];
arr2[0] = 0;
for(int i=0;i<n;i++) {
arr2[i+1] = arr1[i];
}
return arr2;
}
int main()
{
int a1[5] = {1,2,3,4,5}, a2[7]= {7,6,5,4,3,2,1};
int n1= 5, n2 = 7;
int *arr1 = copyArray(a1,n1);
cout<<"First array elements are: ";
for(int i=0;i<n1+1;i++) {
cout<<arr1[i]<<" ";
}
cout<<endl;
int *arr2 = copyArray(a2,n2);
cout<<"Second array elements are: ";
for(int i=0;i<n2+1;i++) {
cout<<arr2[i]<<" ";
}
cout<<endl;
delete arr1;
delete arr2;
return 0;
}
Output:
sh-4.4$ g++ -o main *.cpp
sh-4.4$ main
First array elements are: 0 1 2 3 4 5
Second array elements are: 0 7 6 5 4 3 2 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.