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()
{
        int     day;
        float   temperature[DURATION];
        float   average, total;
        const int DURATION = 5;

        //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 



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


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> temperature[years][month];
                }
        }
}


Back to Main Page for Lecture 5