#include <iostream>
int main() {
int size;
// Prompt the user to enter the size of the array
std::cout << "Enter the size of the array: ";
std::cin >> size;
// Allocate memory dynamically for the array
int* array = new int[size];
// Prompt the user to enter elements for the array
std::cout << "Enter " << size << " elements for the array:\n";
for (int i = 0; i < size; i++) {
std::cin >> array[i];
}
// Display the elements of the array
std::cout << "The elements in the array are:\n";
for (int i = 0; i < size; i++) {
std::cout << array[i] << " ";
}
// Deallocate the dynamically allocated memory
delete[] array;
return 0;
}
Explanation:
- The program begins by declaring an integer variable size, which will store the size of the array that the user will input.
- The user is prompted to enter the size of the array using the std::cout and std::cin statements.
- Memory is allocated dynamically for the array using the new operator. The new operator returns a pointer to the first element of the allocated memory. In this case, the int* variable array is assigned the memory address of the dynamically allocated array.
- The user is then prompted to enter the elements for the array using a for loop. The loop iterates size times, and each element is assigned to the corresponding index of the dynamically allocated array.
- After the user has entered all the elements, the program proceeds to display the elements of the array using another for loop.
- Finally, the delete[] operator is used to deallocate the dynamically allocated memory. It's important to deallocate the memory to avoid memory leaks.
- The program ends with the return 0; statement