Reputation: 11
I have an array with set elements 1 - 10. I have decided the size of the array and I have decided the elements of the array. My question is, how do I create an array of size x and fill it with elements 1,2,3,4 . . .
//sets values of the array elements and print them.
cout << "Array should contain x integers set to 1,2,3" << endl;
// QUESTION: How can I change the size of the array and have
// have values automatically entered?
int array[] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 0; i <= (sizeof(array) / sizeof(int)-1); ++i) {
// sizeof(array)/sizeof(int) = 36/4. ints are 4.
cout << "Element " << i << " = " << array[i] << endl;
}
cout << "The number of elements in the array is: "
<< sizeof(array) / sizeof(int) << endl;
cout << endl;
cout << endl;
Upvotes: 1
Views: 176
Reputation: 75
you can use dynamic memory allocation approach for your array, there you can give as much size as you want. Thanks.
//Variable size of Array program to print Array elements
#include <iostream>
using namespace std;
int main()
{
cout << "Enter Array size x:" << endl;
int x = 0;
cin >> x;
int *ptrArray = new int[x];
//Inittialise Array
for (int i = 0; i < x; i++)
{
ptrArray[i] = i + 1;
}
//Print Array elemts
cout << "Array elements:";
for (int i = 0; i < x; i++)
{
cout << ptrArray[i] << endl;
}
delete[] ptrArray;
return 0;
}
Upvotes: 1