Tuesday, January 31, 2012

4.1.2. Starting value for an array

As we do with the "usual" variables, we can assign a value to the elements of a table at the beginning of the program. Rather than the assigning the values one by one, as we have done in the previous example, we can indicate all the values at a time, separated by comma, inside curly braces:

/*---------------------------*/
/*  C# Example #34:          */
/*  example34.cs             */
/*                           */
/*  Arrays example #2        */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example34
{
  public static void Main()
  {

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

    sum = number[0] +    /* And we calculate the sum */
        number[1] + number[2] + number[3] + number[4];
    Console.WriteLine("Their sum is {0}", sum);
    /* Note: sightly better, but still not the best way */
  }
}


Suggested exercises:
  • A program which stores in a table the number of days in each month (assuming it is a non-leap year), asks the user to indicate a month (1 = January, 12 = December) and displays the number of days in that month. 
  • A program which stores in an array the number of days in each month (for a non-leap year), asks the user for a month (eg 2 for February) and a day (eg day 15) and answers what is the number of that day in the year (eg February 15 would be day number 46, December 31 would be 365).


No comments:

Post a Comment