C ODE IN C++ Using namespace std; Once an array is created, its size is fixed. O
ID: 3710355 • Letter: C
Question
CODE IN C++ Using namespace std;
Once an array is created, its size is fixed. Occasionally, you need to add more values to an array, but the array is full. In this case, you may create a new larger array to replace the existing array. Write a function with the following header:
int* doubleCapacity(const int *list, int size)
The function returns a new array that doubles the size of the parameter 'list'
NOTES:
- The code has to be using only Pointers no array notation
- The function allocates an array that is double the size, note that the return value is a pointer with the address to this larger array
- In the main function, deallocate the smaller array before assigning to the larger array created by doubleCapacity
- Create a dynamically allocated array, and populate it with contents:1, 2, 3, 4, 5
- After calling ‘doubleCapacity’, the array should contain:1, 2, 3, 4, 5, 0, 0, 0, 0, 0
*11.3 (Increase array size) Once an array is created, its size is fixed. Occasionally, you need to add more values to an array, but the array is full. In this case, you may create a new larger array to replace the existing array. Write a function with the following header: int doubleCapacity(const int* list, int size) The function returns a new array that doubles the size of the parameter list.Explanation / Answer
#include<iostream>
using namespace std;
int* doubleCapacity(const int* list, int size){
int dsize = size<<1;
int* doubleList = new int[dsize];
for(int i=0;i<size;i++){
*(doubleList+i) = *(list+i);
}
for(int i=size;i<dsize;i++){
*(doubleList + i) = 0;
}
return doubleList;
}
int main(){
int size = 10;
int* list = new int[size];
for(int i=1;i<=size;i++){
*(list+(i-1)) = i;
}
int* doubleList = doubleCapacity(list, size);
for(int i=0;i<2*size;i++){
cout << *(doubleList+i)<<" ";
}
return 0;
}
output:
1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0
NOTE: The size variable has been initialized with 10. You can change it and the code will give output accordingly. You can also initialize the values with your choice in the list variable.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.