Monday, January 30, 2012

4.1.1. Defining an array and accessing the data


4. Arrays, structures and strings

4.1. Basic concepts on arrays

4.1.1. Defining an array and accessing the data

A table, vector, matrix or array is a set of elements, all of which are the same type. These elements will all have the same name, and occupy a contiguous space in memory.

For example, if we define a set of numbers, the we will use "int []" as data type. If we know from the beginning how much data we have (eg 4 numbers), we can reserve space with "= new int [4]", like this:

int[] example = new int[4];

We can access each individual value with the name of the variable (example) and the number of the item we want to access. First element is number 0, so in the previous example we would have 4 elements, named example[0], example[1], example[2], example[3].

As an example, let's define a set of 5 integers and calculate their sum:

/*---------------------------*/
/*  C# Example #33:          */
/*  example33.cs             */
/*                           */
/*  Arrays example #1        */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example33
{
  public static void Main()
  {

    int[] number = new int[5];     /* An array for 5 integers */
    int sum;              /* An integer for the sum */

    number[0] = 200;      /* We assign values */
    number[1] = 150;
    number[2] = 100;
    number[3] = -50;
    number[4] = 300;
    sum = number[0] +     /* And we calculate the sum */
        number[1] + number[2] + number[3] + number[4];
    Console.WriteLine("Their sum is {0}", sum);
    /* Note: this an inefficient way. We'll improve it later */
  }
}



Suggested exercises:
·       A program that asks the user for 4 numbers, stores them (using an array), calculates their average and then displays the average and the entered data.
·       A program that asks the user for 5 real numbers and then displayed in the reverse order.
·       A program that asks the user 10 integers, and calculates (and shows) which one is the greatest.

No comments:

Post a Comment