ch05 (1) - Arrays
ch05 (1) - Arrays
Arrays, Qualifiers
and Reading
Numbers
Practical C++ Programming Copyright 2003 O'Reilly and Associates Page1
Arrays
Arrays are used to store a collection of related values.
Instead of declaring a individual variable in which to store
each value, you can declare the array.
Array declaration has the format:
data type arrayname[n];
where n is a positive integer constant that represents the
maximum number of values, elements, that you want to
store in the array -- size declarator.
e.g.
double hello[3];
int alpha[20];
Practical C++ Programming Copyright 2003 O'Reilly and Associates Page2
Arrays
Simple variables allow user to declare one item, such as a single width:
int width; // Width of the rectangle in inches
If we have a number of similar items, we can use an array to declare them. For
example, if we want declare a variable to hold the widths of 1000 rectangles.
int width_list[1000]; // Width of each rectangle
The width of the first rectangle is width[0] the width of the second rectangle is
width[1] and so on until width[999].
Warning:
Common sense tells you that the last element of the width array is width[1000].
Common sense has nothing to do with programming and the last element of the
array is width[999].
As an array
OR (if there is a patter or you cin each value use a for loop)
int nums[3];
for (int i=0;i<3;i++){
nums[i]=(i+1)*2;
}
double data[5]; // data to average and total
double total; // the total of the data items
double average; // average of the items
int main()
{
data[0] = 34.0;
data[1] = 27.0;
data[2] = 46.5;
data[3] = 82.0;
data[4] = 22.0;
total = data[0] + data[1] + data[2] + data[3] + data[4];
average = total / 5.0;
cout << "Total "<< total <<" Average "<< average << '\n';
system(“pause”);
}
double data[5]; // data to average and total
double total; // the total of the data items
double average; // average of the items
int main()
{
data[0] = 34.0;
data[1] = 27.0;
data[2] = 46.5;
data[3] = 82.0;
data[4] = 22.0;
for(int i=0;i<4;i++){
total+=data[i];
}
average = total / 5.0;
cout << "Total " <<total<<" Average " <<average<< '\n';
system(“pause”);
}