input N numbers
Array syntax
type arrayName[dimension];
Array initialization
int A[MAXSIZE] = { 11, 22, 33, 44, 55 };
// declare a fixed size array and initialize the elements... note that MAXSIZE can be larger than 5....
or
int A[] = { 11, 22, 33, 44, 55 };
// declare a fixed size array and initialize the elements... note that A has 5 elements exactly....
Note that dynamic array such as int *arrayPT = new int[MAXSIZE] ; can not be initialized
Ask N, prompt for each and store them in a static array
int A[MAXSIZE];
cout << "how many?" << endl;
cin >> n; // check size
for (int i=1; i<=n; i++) {
cout << "input number #" << i << " followed by enter:" << endl;
cin >> A[i-1]; // array index starts from 0
}
Ask N, prompt for all in one line and store them in a static array
int A[MAXSIZE];
cout << "how many?" << endl;
cin >> n; // check size
cout << "enter all numbers separate by space" << endl;
for (int i=0; i<n; i++) {
cin >> A[i];
}
Ask N, prompt for each and store them in a dynamic array
cout << "how many?" << endl;
cin >> n;
int * arrayPT = new int (n);
int * pt = arrayPT;
for (int i=1; i<=n; i++) {
cout << "input number #" << i << " followed by enter:" << endl;
cin >> *pt;
pt++;
}
Prompt and store them in a vector (taken from here)
std::vector<int> myvector;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
vector initialization is quite different from array.
it should be straightforward to change the above code to "Ask N"
Note:
Even though we use int as example, it should be obvious that int can easily be replaced with any other object. The only thing it needs to have is the operator >> overloading.
One more variation is to create a new obj for each input. But we will need to have a "container" to store these pointers. The code will be similar to the vector example above.
The more meaningful scenario is to create a new obj for each input and organize these objects in a link list.