Arrays and Structures
Source Code from Notes
Example
Program to input each of the temperatures over the 30 days to calculate the
average
temperature during the period.
// Program to input 30 temperature samples and calculate their average
#include <iostream.h>
main()
{
const int DURATION = 5;
int day;
float temperature[DURATION];
float average, total;
//Enter temperature values
for (day =0; day < DURATION ;day++)
{
cout << "Enter temperature of day " << day << "\n";
cin >> temperature[day];
}
// initialise total variable
total = 0.0;
// sum temperatures for each day
for (day=0; day < DURATION; day++)
{
total += temperature[day];
}
// calculate average
average = total/DURATION;
//output result
cout << "The average temperature is" << average << "\n";
}
Example
The following example reads in a sentence which is terminated by a full
stop and calculates the number of lower case vowels in the sentence. An
array of char elements is defined. The length of this array is
limited to 100 elements.
// Program to count for number of vowels in a sentence
// the sentence must be terminated by a full stop (.)
#include <iostream.h>
main()
{
const int max_length = 100; //max number of characters in sentence
char sentence[max_length];
int i,count,length;
i = 0;
count = 0;
// enter the sentence
cout << "Enter a sentence terminated by a full stop \n";
do {
cin >> sentence[i];
i++;
} while(sentence[i-1] != '.' && i < max_length);
// number of characters in sentence
length = i;
// count number of lower case vowels
for (i=0;i < length;i++) {
if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i]
== 'i' || sentence[i] == 'o' || sentence[i] =='u') {
count++;
}
}
// output number of vowels
cout << "The number of lower case vowels is " << count << "\n";
}
Example
Two dimensional array example where the
average temperature each month for the last 20 years is declared and the user
is then prompted to enter the values
#include <iostream.h>
main()
{
const int NO_MONTHS = 12;
const int NO_YEARS = 20;
float temperature[NO_YEARS][NO_MONTHS];
int years,month;
// input values to array
for (years = 0;years < NO_YEARS;years++)
{
for (month=0;month < NO_MONTHS;month++)
{
cout << "Enter temperature ";
cin >> temperature[years][month];
}
}
}