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 <stdio.h>
#define DURATION 30
main()
{
int day;
float temperature[DURATION];
float average, total;
/*Enter temperature values */
for (day =0; day < 30;day++)
{
printf("Enter temperature of day %d\n",day);
scanf("%f",&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 */
printf("The average temperature is %f\n",average);
}
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 <stdio.h>
#define max_length 100 /*max number of characters in sentence */
main()
{
char sentence[max_length];
int i,count,length;
i = 0;
count = 0;
/* enter the sentence */
printf("Enter a sentence terminated by a full stop \n");
do {
scanf("%c",&sentence[i]);
i++;
} while(sentence[i-1] != '.' && i < max_length);
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 */
printf("The number of lower case vowels is %d\n",count);
}
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 <stdio.h>
#define NO_MONTHS 12
#define NO_YEARS 20
main()
{
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_MONTH;month++)
{
printf("Enter temperature ");
scanf("%f",&temperature[years][month]);
}
}
}