Wednesday, February 1, 2012

4.1.3. Visiting the table elements

As we could expect, there is a more convenient way to access various elements of an array, not needing to repeat them all, as we have done in

   sum = number[0] + number[1] + number[2] + number[3] + number[4];

The "trick" will be using any repetitive structure (while, do...while, for), such as:

    sum = 0;              // Starting value for the sum
    for (i=0; i<=4; i++) // And we calculate it in an iterative way
      sum += number[i];

The full program might be:

/*---------------------------*/
/*  C# Example #35:          */
/*  example35.cs             */
/*                           */
/*  Arrays example #3        */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example35
{
  public static void Main()
  {

    int[] number =            // An array for 5 integers
      {200, 150, 100, -50, 300};
    int sum;                  // An integer for the sum
    int i;                    // To iterate through the elements

    sum = 0;              // Starting value for the sum
    for (i=0; i<=4; i++) // And we calculate it in an iterative way
      sum += number[i];

    Console.WriteLine("Their sum is {0}", sum);
  }
}


In this case, as we were adding only 5 numbers, we have not written far less than with the previous version of the program, but if we were using 100, 500 or 1000 numbers, the gain would be obvious.

No comments:

Post a Comment