C++ Program to Implement Variable Length Array


Variable length arrays can have a size as required by the user i.e they can have a variable size.

A program to implement variable length arrays in C++ is given as follows −

Example

 Live Demo

#include <iostream>
#include <string>

using namespace std;
int main() {
   int *array, size;
   cout<<"Enter size of array: "<<endl;
   cin>>size;
   array = new int [size];
   cout<<"Enter array elements: "<<endl;

   for (int i = 0; i < size; i++)
   cin>>array[i];
   cout<<"The array elements are: ";

   for(int i = 0; i < size; i++)
   cout<<array[i]<<" ";
   cout<<endl;
   delete []array;
   return 0;
}

The output of the above program is as follows −

Enter size of array: 10
Enter array elements: 11 54 7 87 90 2 56 12 36 80
The array elements are: 11 54 7 87 90 2 56 12 36 80

In the above program, first the array is initialized. Then the array size and array elements are requested from the user. This is given below −

cout<<"Enter size of array: "<<endl;
cin>>size;

array = new int [size];

cout<<"Enter array elements: "<<endl;

for (int i = 0; i < size; i++)
cin>>array[i];

Finally, the array elements are displayed and the array is deleted. This is given below −

cout<<"The array elements are: ";
for(int i = 0; i < size; i++)
cout<<array[i]<<" ";
cout<<endl;
delete []array;

Updated on: 25-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements