You are on page 1of 23

Luis 

Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 375
Homogeneous Collections
Same data type for a collection of data:
Grades for the students in a class, sale for every weekday,
temperature for every day in the month, ...
Instead of declaring N variables...
sMon sTue sWed sThu sFri sSat sSun
125.40 76.95 328.80 254.62 435.00 164.29 0.00

... we declare a table of N values:


Luis Hernández Yáñez

sales 125.40 76.95 328.80 254.62 435.00 164.29 0.00


Indexes 0 1 2 3 4 5 6

Fundamentals of Programming I: Types and Instructions II Page 376
Sequential Structure
Each element in a specific position (index):
 Indexes are positive integers
 The index of the first element is always 0
 Indexes are incremented by one
sales 125.40 76.95 328.80 254.62 435.00 164.29 0.00
0 1 2 3 4 5 6
Direct Access
Each element is accessed by its index with the operator []:
sales[4] accesses the 5th element (it contains the value 435.00)
Luis Hernández Yáñez

cout << sales[4];
Data of the same base type:
sales[4] = 442.75; Used as any other variable
Fundamentals of Programming I: Types and Instructions II Page 377
Array Type Declaration
typedef base_type type_name[length];
Examples:
typedef double tTemp[7];
typedef short int tMonthDays[12];
typedef char tVowels[5];
typedef double tSales[31];
typedef tCoin tChange[15]; // Enumerated base type
Luis Hernández Yáñez

Remember: We create type names by starting with a lowercase t


followed by one or more words with their first letter capitalized

Fundamentals of Programming I: Types and Instructions II Page 378
Array Variable Declaration typedef
typedef
double tTemp[7];
short int tMonthDays[12];
typedef char tVowels[5];
type_name variable_name; typedef double tSales[31];
Examples:
tTemp tempMax; tempMax ? ? ? ? ? ? ?
0 1 2 3 4 5 6

tMonthDays days; days ? ? ? ? ? ? ? ? ? ? ? ?


0 1 2 3 4 5 6 7 8 9 10 11

tVowels vowels; vowels ? ? ? ? ?


0 1 2 3 4

...
tSales maySales; maySales ? ? ? ? ? ? ? ? ? ? ? ? ? ?
Luis Hernández Yáñez

0 1 2 3 4 5 6 7 8 9 10 11 12 30

Elements are NOT automatically initialized


Fundamentals of Programming I: Types and Instructions II Page 379
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 380


typedef char tVowels[5];

name[index]
Each element is accessed by its index (position in the array)
tVowels vowels; vowels 'a' 'e' 'i' 'o' 'u'
0 1 2 3 4

5 elements, indexes from 0 to 4:


vowels[0]   vowels[1]   vowels[2]   vowels[3]   vowels[4]
Processing each element:
As any other variable of that base type
cout << vowels[4];
Luis Hernández Yáñez

vowels[3] = 'o';
if (vowels[i] == 'e') ...

Fundamentals of Programming I: Types and Instructions II Page 381
IMPORTANT!
The compiler doesn't test if the index is valid!
It is the programmer's responsibility!

const int Dim = 100; Declare the length of the arrays as a constants


typedef double tSales[Dim];
tSales sales;
Valid indexes: integers from 0 to Dim-1
sales[0]   sales[1]   sales[2] ... sales[98]   sales[99]
Luis Hernández Yáñez

What is sales[100]? Or sales[‐1]? Or sales[132]?

Memory of another program's variable!


Fundamentals of Programming I: Types and Instructions II Page 382
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 383
Arrays: Fixed length  Fixed number of iterations loop (for)
Example: Mean of a sequence of temperature measures
const int Days = 7;
typedef double tTemp[Days];
tTemp temp;
double mean, total = 0; 
...
for (int i = 0; i < Days; i++)
total = total + temp[i];
mean = total / Days;
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 384
12.40 10.96 8.43 11.65 13.70 13.41 14.07
tTemp temp; 0 1 2 3 4 5 6
double mean, total = 0; 
... Memoria

for (int i = 0; i < Days; i++) Days 7


temp[0] 12.40
total = total + temp[i]; temp[1] 10.96
temp[2] 8.43
temp[3] 11.65
i = 0
temp[4] 13.70
temp[5] 13.41
true false
i<Days temp[6] 14.07
mean ?
total+=temp[i] ...
Luis Hernández Yáñez

total 84.62
23.36
31.79
12.40
0.00
43.44

i++ i 3
70
2
4
1

Fundamentals of Programming I: Types and Instructions II Page 385
tempmean.cpp

#include <iostream>
using namespace std;
const int Days = 7;
typedef double tTemp[Days]; Users use 1 to 7 to enumerate days
Program interface must be user-friendly,
double mean(const tTemp temp); although internally indexes from 0 to 6 are used

int main() {
tTemp temp;
for (int i = 0; i < Days; i++) { // Array traversal
cout << "Temperature of the day " << i + 1 << ": ";
cin >> temp[i];
}
Luis Hernández Yáñez

cout << "Mean temperature: " << mean(temp) << endl;
return 0;
} …/…

Fundamentals of Programming I: Types and Instructions II Page 386
double mean(const tTemp temp) {
double meanValue, total = 0; 

for (int i = 0; i < Days; i++) // Array traversal


total = total + temp[i];
meanValue = total / Days;

return meanValue;
}
Luis Hernández Yáñez

Arrays are passed to functions as constants


Functions can't return arrays

Fundamentals of Programming I: Types and Instructions II Page 387
const int HowMany = 15;
typedef enum {cent, two_cents, five_cents, ten_cents,
twenty_cents, half_euro, euro } tCoin;
typedef tCoin tChange[HowMany];
string toString(tCoin coin); // Corresponding string
// In main()...
tChange pocket; // Exactly HowMany coins
pocket[0] = euro;
pocket[1] = five_cents;
pocket[2] = half_euro;
pocket[3] = euro;
pocket[4] = cent;
Luis Hernández Yáñez

...
for (int coin = 0; coin < HowMany; coin++)
cout << toString(pocket[coin]) << endl;
Fundamentals of Programming I: Types and Instructions II Page 388
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 389
searcharray.cpp

Which day were sales higher than 1,000 €?


const int Days = 365; // Not a leap year
typedef double tSales[Days];
int search(const tSales sales) { // First element > 1000 or ‐1
bool found = false;
int ind = 0;
while ((ind < Days) && !found) // Search Scheme
if (sales[ind] > 1000)
found = true;
else
ind++;
if (!found) // If not found, ‐1 is returned
Luis Hernández Yáñez

ind = ‐1;
return ind;
}
Fundamentals of Programming I: Types and Instructions II Page 390
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 391
The capacity of an array can't be changed during execution
Array length is a design decision:
 Sometimes it will be easy (days of a week)
 When it can be different from one execution to other,
an estimated maximum length should be used
Neither too short, nor with a lot of free space

Dynamic arrays (FP2) can be created on the fly


C++ STL (Standard Template Library):
Luis Hernández Yáñez

More efficient collections with the length dynamically managed

Fundamentals of Programming I: Types and Instructions II Page 392
An array can't be copied using the assignment operator:
array2 = array1; // ELEMENTS ARE NOT COPIED!!!

We have to copy the array element by element:


for (int i = 0; i < N; i++)
array2[i] = array1[i];
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 393
Luis Hernández Yáñez

Fundamentals of Programming I: Types and Instructions II Page 394
We may not need all the positions in an array...
The length of the array will be the maximum number of elements
There may be fewer elements than the maximum
We need an element counter...
const int Max = 100;
typedef double tArray[Max];
tArray list;
int counter = 0;
counter: indicates how many positions are used
Luis Hernández Yáñez

We will only access positions between 0 and counter-1


The rest of the positions don't contain program information
Fundamentals of Programming I: Types and Instructions II Page 395
list.cpp

#include <iostream>
#include <fstream>
using namespace std;
const int Max = 100;
typedef double tArray[Max];
double mean(const tArray list, int count);

int main() {
tArray list;
int counter = 0;
double value, m;
ifstream file;
file.open("list.txt");
if (file.is_open()) {
file >> value;
while ((value != ‐1) && (counter < Max)) {
Luis Hernández Yáñez

list[counter] = value;
counter++;
file >> value; …/…
}
Fundamentals of Programming I: Types and Instructions II Page 396
file.close();
m = mean(list, counter);
cout << "Mean of list elements: " << m << endl;
}
else
cout << "File couldn't be opened!" << endl;

return 0;
}

double mean(const tArray list, int count) {


double meanValue, total = 0;
for (int ind = 0; ind < count; ind++)
total = total + list[ind];
Luis Hernández Yáñez

meanValue = total / count;
return meanValue; We will end at count-1
}
Fundamentals of Programming I: Types and Instructions II Page 397

You might also like