In: Computer Science
in C++
In this third part, write a function that accepts an array of integers and its size as arguments. The function should create a new array that is of half size the argument array (round up the fraction if the size of the argument array is odd). The value of the first element (Element 0) of the new array should be the sum of the first two elements of the argument array (Element 0 and 1). Element 1 of the new array should be the sum of Element 2 and 3 of the argument array, and so forth. If the size of the argument array is odd, then the last element of the new array should be the same as the last element of the argument array. The function should return a pointer to the new array to the main. IN THIS FUNCTION AND THIS FUNCTION
Hi, Please find my implementation.
Please let me know in case of any issue.
#include
#include
using namespace std;
// function declaration
int *halfArray(int *arr, int size){
int newlen = size%2==0 ?size/2 : (size/2+1);
int *newArr = new int[newlen];
int i=0, k=0;
while(i < size-1){
*(newArr + k) = *(arr+i)+
*(arr+i+1);
k = k+1;
i = i+2;
}
if(newlen%2 == 1)
*(newArr+k) = *(arr+i);
return newArr;
}
int main(){
int arr[] = {1,2,3,4,5,6,7,8,9};
int *newArr = halfArray(arr, 9);
cout<<"Old Array: "< cout<<"New Array: "<
cout<<*(arr+i)<<"
";
cout<
cout<<*(newArr+i)<<"
";
cout<
return 0;
}