C++ Program to Implement Variable Length Array

C++ProgrammingServer Side Programming

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;
raja
Published on 22-Oct-2018 17:50:15
Advertisements