PIC10A Lecture 12

Reading

170-181

Array

Example
#include <iostream>
using namespace std;

// the program asks user to input 5 numbers
// then output the average
int main() {
// declare an array with 5 numbers
// sum is the total sum of all the scores
double score[5], sum = 0;
cout << "Please input 5 numbers. "
<< "Seperate the numbers by spaces: \n";

int i;
for(i = 0; i < 5; i++) {
cin >> score[i]; //ask the user to input the i-th score
sum+=score[i];
}

// magic formula
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The scores are : \n";

for(i = 0; i < 5; i++) {
cout << score[i] << " ";
}

cout << endl;
cout << "The average is " << sum/5 <<endl;

return 0;

}

Output
Please input 5 numbers. Seperate the numbers by spaces:
92.25 33 45.75 88.8 77.77
The scores are :
92.25 33.00 45.75 88.80 77.77
The average is 67.51

score[0] score[1] score[2] score[3] score[4]
92.25 33 45.75 88.8 77.77
Explanation of the program Array consists of 2 parts Syntax
Declare an array
Type arrayName[size];

size should be a number or a const variable. It shouldn't be other type of variables.
Example: Access elements in an array
Individual parts called many things Note the 2 uses of brakets [] Natural counting loop
Naturally works well ‘counting thru’ elements of an array.
    for(i = 0; i < NUM_OF_STUDENTS; i++) {
cin >> score[i]; //ask the user to input the i-th score
sum+=score[i];
}
Major array pitfall

Arrays in memory

Refer to the book, p178, Display 5.2

Initializing array

Array can be initialized like this
int children[3] = {2, 12, 1};
It is equivalent to the following code
int children[3];
children[0]=2;
children[1]=12;
children[2]=1;
If you initialize an array when it is declared, you can omit the size of the array, and the array will automatically be declared to have the minmum size needed for the initialization values.
int b[] = {5, 12, 11};
is equivalent to
int b[3] = {5, 12, 11};
Example
#include<iostream>
using namespace std;

int main(){
int array[5] = {1,3,5};
int i;
for(i = 0; i < 5; i++) {
cout << array[i] << " ";
}
cout << endl;
return 0;

}
Output
1 3 5 0 0