Accessing the fields of a structure
Now,
when referring to individual items of data,
we need to first specify which team we're interested in,
and then which field of that team's structure.
We use a single dot ('.' or fullstop)
to separate the variable name from the field name.
The old way, with independent variables:
// PRINT EACH TEAM'S RESULTS, ONE-PER-LINE, IN NO SPECIFIC ORDER
for(int t=0 ; t<nteams ; ++t) {
printf("%s %i %i %i %i %i %i %.2f %i\n", // %age to 2 decimal-places
teamname[t],
played[t], won[t], lost[t], drawn[t],
bfor[t], bagainst[t],
(100.0 * bfor[t] / bagainst[t]), // calculate percentage
points[t]);
}
|
The new way, accessing fields within each structure:
// PRINT EACH TEAM'S RESULTS, ONE-PER-LINE, IN NO SPECIFIC ORDER
for(int t=0 ; t<nteams ; ++t) {
printf("%s %i %i %i %i %i %i %.2f %i\n", // %age to 2 decimal-places
team[t].teamname,
team[t].played, team[t].won, team[t].lost, team[t].drawn,
team[t].bfor, team[t].bagainst,
(100.0 * team[t].bfor / team[t].bagainst), // calculate percentage
team[t].points);
}
|
While it requires more typing(!),
it's clear that the fields all belong to the same structure (and thus team).
Moreover,
the names teamname, played, ....
may now be used as "other" variables elsewhere.
CITS2002 Systems Programming, Lecture 5, p13, 5th August 2024.
|