Sunday, October 15, 2006

What are arrays for?

Before we go into other nice things we can do with arrays, let us look at why we need arrays at all?

Let's say, we have the ages of 6 people and we are asked to write a program to calculate mean(average). What would our program look like?
Maybe something like this:

public double calcAverageAge (int johnAge,
      int janniAge,
      int janardhanAge,
      int AmarAge,
      int AkbarAge,
      int AnthonyAge)
   double averageAge = (johnAge + janniAge + janardhanAge + AmarAge + AkbarAge + AnthonyAge)/6;
   return averageAge;

Now, supposing, we were to be asked to do the same for 100 or a 1000 people. If we continue with the way we are going, we would soon be up sh*tcreek without a paddle. What we will need is a nice way to access the ages of a 100, 1000 or any reasonable number of people using a single variable.

That is where an array comes in. With an array, our function would look like

public double calcAverageAge (int [] ages, int noOfPeople)
   double sumOfAges = 0;
   double averageAge = 0;
   for (int i = 0; i < noOfPeople; i++)
      sumOfAges += ages[i];
   averageAge = sumOfAges/noOfPeople;
   return averageAge;
public void callAverage()
   int noOfStudents = 100;
   int [] agesOfStudents = new int[100];
/* from file or database fill up the the ages array with values */
   double avgAge = calcAverageAge(agesOfStudents, noOfStudents);

As you can see, arrays provide us a nice way to handle situations where we have to access and manipulate many variables of the same data type.

Every once in a while, we should take our heads out of the details and look for the "raison d'etre", question the obvious, take a closer look at the trees, whatever.

1 comment:

Bosky said...

interesting point made with limiting parameters to functions . I even stumbled upon a concept in functional programming called currying as a result of finding out more about the idea you were expressing .thnx for provoking me to check out arrays and currying ...