In: Computer Science
In c++
Array expander
Write a function that accepts an int array and the arrays size as arguments.
The function should create a new array that is twice the size of the argument array.
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.
Additional Requirements:
A 20-Point Sample Run:
8 6 7 5 3 0 0 0 0 0
In the sample run, the original array was initialized with 8 6 7 5 3.
#include <iostream>
using namespace std;
int* doubleArray(int* A, int n){
// creating the array dynamically
// double the size of original array
int* B = new int[2 * n];
// initializing the first n elements with
// the corresponding elements of original array
for(int i = 0; i < n; i++)
B[i] = A[i];
// initializing the remaining elements with 0
for(int i = n; i < 2 * n; i++)
B[i] = 0;
return B;
}
int main(){
int n = 5;
int A[n] = {8, 6, 7, 5, 3};
// calling the doubleArray method
int* B = doubleArray(A, n);
for(int i = 0; i < 2 * n; i++)
cout << B[i] << " ";
// deleting the array
delete B;
return 0;
}
OUTPUT:-
if you have any doubt, feel free to ask in the comments.