/* Examples of typical uses of arrays Laura Toma Csci 107 */ #include int main() { //declare a constant indicating the number of items in the array const int NUM = 10; int i, below; //declare an array that can hold NUM items; the array is not //initialized, that is, its contents are garbage until a value is //assigned to each item in the array int a[NUM]; //assign values to the items in the array //you can assign a value to a particular item in the array, as //the following statement shows: //a[3] = 25; //but doing something to ALL items in the array is far more common //than doing something to a single item; below we read the values //in the array, one by one, from the user; you can use cin to put //values from the user directly into the array i = 0; while (i< NUM) { //read a value into the i-th item cout <<"Enter a value for element " << i << ":"; cin >> a[i]; i = i+1; } //print the array i = 0; cout << "You entered the array: "; while (i< NUM) { //print the value in the i-th item followed by a space cout << a[i] << " "; i = i+1; } //print a new line at the end cout << endl; //now we do something with the array; for instance, let's assume we //want to count how many items in the array are negative; i = 0; below = 0; //nb of items below zero while (i< NUM) { if (a[i] <0) below = below + 1; i = i+1; } //now we print what we found cout <<"The array contains " << below << " negative items\n"; return 0; }