Dynamic Array Allocation

Dynamic Array Allocation Program in C++

BeginnerTopic: Memory Management Programs
Back

C++ Dynamic Array Allocation Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int size;
    
    cout << "Enter array size: ";
    cin >> size;
    
    // Dynamically allocate array
    int* arr = new int[size];
    
    cout << "Enter " << size << " elements: ";
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }
    
    cout << "\nArray elements: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Calculate sum
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    
    cout << "Sum: " << sum << endl;
    cout << "Average: " << (double)sum / size << endl;
    
    // Find max and min
    int max = arr[0], min = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) max = arr[i];
        if (arr[i] < min) min = arr[i];
    }
    
    cout << "Maximum: " << max << endl;
    cout << "Minimum: " << min << endl;
    
    // Free memory
    delete[] arr;
    arr = nullptr;
    
    return 0;
}
Output
Enter array size: 5
Enter 5 elements: 10 20 30 40 50
Array elements: 10 20 30 40 50
Sum: 150
Average: 30
Maximum: 50
Minimum: 10

Understanding Dynamic Array Allocation

Dynamic array allocation allows you to create arrays whose size is determined at runtime. This is useful when the size is not known at compile time. Use new[] to allocate and delete[] to free. Dynamic arrays are stored on the heap, allowing larger sizes than stack arrays. Always free dynamically allocated memory to prevent leaks.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents