Monday, 30 May 2011

Arrays

If you have collection of similar data elements, you may find it inconvenient to give each one a unique variable name. For instance, suppose you wanted to find the average temperature for a particular week. If each day's temperature had a unique variable name, you would end up reading in each value separately like this:


printf("Enter Sunday Temperature: ");   
scanf("%d",&suntmp);
printf("Enter Monday Temperature: ");
scanf("%d",&montmp);
---------------


and so on for each day of the week, with an expression for the average such as this:


(suntmp+montmp+tuetmp+wedtmp+thutmp+fritmp+sattmp)/7


This is on altogether unwieldy business, especially if you want to average the temperature for a month or a year.
 Clearly we need a convenient way to refer to such collections of similar data elements. The array fills the bill. It provides a way to refer to individual items in a collection by using the same variable name, but differing subscripts, or numbers. Let's see how we'd solve our problem of averaging the temperature for a week using arrays:


void main()
{
 int temper[7];
 int day,sum;


 for(day=0;day<7;day++)
 {
  printf("Enter Temperature for day %d: ",day);
  scanf("%d",&temper[day]);
 }

 sum=0;
 for(day=0;day<7;day++)
  sum+=temper[day];
 printf("Average is %d.",sum/7);





This program reads in seven temperatures, stores them in an array and then, to calculate an average temperature, reads them back out of the array, adding them together, and divide by 7. Here's a result:


Enter Temperature for day 0: 74
Enter Temperature for day 1: 76
Enter Temperature for day 2: 77
Enter Temperature for day 3: 77
Enter Temperature for day 4: 64
Enter Temperature for day 5: 66
Enter Temperature for day 6: 69
Average is 71.


If you have any question, you can ask me freely!

0 comments:

Post a Comment