Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ เพื่อใช้งาน Variable Length Array


อาร์เรย์ความยาวผันแปรสามารถมีขนาดตามที่ผู้ใช้ต้องการได้ นั่นคือสามารถมีขนาดตัวแปรได้

โปรแกรมที่ใช้อาร์เรย์ความยาวผันแปรใน C ++ ได้รับดังนี้ -

ตัวอย่าง

#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;
}

ผลลัพธ์ของโปรแกรมข้างต้นเป็นดังนี้ −

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

ในโปรแกรมข้างต้น อาร์เรย์จะเริ่มต้นขึ้นก่อน จากนั้นผู้ใช้จะขอขนาดอาร์เรย์และองค์ประกอบอาร์เรย์ ด้านล่างนี้ −

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;