DYNAMIC ARRAY
unknown
c_cpp
a year ago
2.7 kB
4
Indexable
// DYNAMIC ARRAYS #include <iostream> #include <limits> using namespace std; // Function Prototype void insert(int *arr, unsigned int &size, unsigned int &allocted_size); // Driver Code int main() { unsigned int size; unsigned int allocated_size = 0; cout << "Enter the size of the array : "; while (!(cin >> size)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Please enter a valid input : "; } // Dynamic Memory Allocation int *arr = new int[size]; cout << "An array of size " << size << " has been created successfully." << endl; // Function Calls insert(arr, size, allocated_size); insert(arr, size, allocated_size); insert(arr, size, allocated_size); return 0; } // Insert Function : This function takes the integer from the user and pushes in into the array and if the space is full then it expands the array and then inserts the value void insert(int *arr, unsigned int &size, unsigned int &allocted_size) { // User Input int value; cout << "Enter the value to be inserted in the array : "; while (!(cin >> value)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Please enter a valid int input : "; } // If the allocated size is less then the actual size of the array then push the element into the array and increment the allocated_size value by one if (allocted_size < size) { *(arr + allocted_size) = value; cout << "Successfully inserted " << value << " at index " << allocted_size << endl; allocted_size++; } // If the allocated size is equal to or more than then the actual size of the array then expand the array and push the element into the array else { size = size + 1; int *newarr = new int[size]; // copying the elements of old array to newly created array for (size_t i = 0; i < size; i++) { *(newarr + i) = *(arr + i); } // pushing the element *(newarr + allocted_size) = value; cout << "Successfully expanded the array and inserted " << value << " at index " << allocted_size << endl; allocted_size++; // deallocating the space of new array delete[] arr; // pointing the old array pointer to the new array arr = newarr; } // printing all the elements present int the array for (size_t i = 0; i < allocted_size; i++) { cout << *(arr + i) << " is at index " << i << endl; } }
Editor is loading...
Leave a Comment