I can help you with number 2:
In order to allow the user to input the size of the array, you have 2 options:
1) Create a very large array, such as int array[1000]. Ask the user for input into a variable size, and then perform operations only on array[0]...array[size-1]; For example:
- int array[1000];
-
int size;
-
cout << "How many values? ";
-
cin >> size;
-
for (int i = 0; i < size; i++) {
-
cout << "Enter value " << i + 1 << ": ";
-
cin >> array[i];
-
}
However, there is a lot of wasted computer space, since a user may enter a small value (such as 10) for size and leave 990 integer values unused.
Therefore, the much better solution is
2) Use pointers. A pointer is a special type of variable most useful for this type of array and large data structures. It would be impossible for me to fully explain pointers to you, so I will limit my description to pointer arrays.
You know that you cannot execute the following statements:
- int size;
-
cout << "Please enter the size: ";
-
cin >> size;
-
int array[size]; // Error! C++ requires a constant
However, by making array a pointer, you can do this. To make array a pointer, use this statement:
- int *array; // NOT int array[whatev];
Then you can prompt the user for input into size, and finally say
For general purposes, these are the only changes you need to know about for pointers. You can now treat array the same as a regular integer array.
Your resulting code would be:
- int size;
-
int *theArray;
-
cout << "Please input the size: ";
-
cin >> size;
-
theArray = new int[size];
-
-
for (int i = 0; i < size; i++) {
-
cout << "Please enter value " << i + 1 << ": ";
-
cin >> theArray[i];
-
}