Q / This is the solution of my assignment, which me have done with very hardworking.I want you to check it properly and if you can suggest an alternative solution please do it for me or if you can make some changes then help me to provide so different solution.
Problem Statement:
Dynamic memory allocation/reallocation of an Integer array.
Detailed Description:
Write a program in which you have to:
1. Dynamically allocate an array of integers.
2. Take array size as input from user and allocate memory according to this size.
3. Take values of array elements as an input from user.
4. Print all array values.
5. In this step; double the previous array size (taken in step 2) and reallocate memory for the array according to new array size. For example if user provided array size is 4; now it will become 8, i.e. allocate memory for array having size 8.
6. Now again take values for second half of the array as an input from the user to fill the increased size of an array.(You have already taken the values of first half of the array elements in step 3, now take values for remaining elements i.e. Second half).
7. Print all values of the array.
8. Also confirm that first half values of array are same in both printout statements (step 3 and step 7).
Sample Output
Program to dynamically Allocates an array of integers.
Enter the size of the array: 4
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
The elements of the array are:
1 2 3 4
Enter the elements in the array after reallocation:
Enter a value: 5
Enter a value: 6
Enter a value: 7
Enter a value: 8
1 2 3 4 5 6 7 8
Solution:
Code:#include<iostream> using namespace std; //by PM 22 MAY 2009 int main() { int size = 0;//hold size of array int count = 0;//counter for loops //get size from user cout<<"Enter the size of array: "<<endl; cin>>size; //create array int * numbers; numbers = new int[size]; //get numbers from user for(count = 0; count < size; count++) { cout<<"Enter value number "<<count + 1<<endl; cin>>numbers[count]; }//end for //print array for(count = 0; count < size; count++) { cout<<numbers[count]<<endl; }//end for //create new array int * nextNumbers; nextNumbers = new int[size*2]; //copy old array to new array for(count = 0; count < size; count++) { nextNumbers[count] = numbers[count]; }//end for //delete old array delete[] numbers; //get numbers from user for(int index= count ; index < size*2; index++) { cout<<"Enter value number "<<index + 1<<endl; cin>>nextNumbers[index]; }//end for //print array for(count = 0; count < size*2; count++) { cout<<nextNumbers[count]<<endl; }//end for //delete array delete[] nextNumbers; }//end main