4.0 Arrays

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it Arrays

Discussion

An array stores a collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at similar memory locations.

Visualization

class Program
{
//     1       2     3    4    5
    string[] food = new string[4];
//      6
        food[0] = "Macaroni";
        food[1] = "Pasta";
        food[2] = "Pizza";
        food[3] = "Popcorn";
}
  1. Declaring an array that will hold string values

  2. Name of the array

  3. Using keyword new to instantiate a new array

  4. Will hold string values

  5. The array will hold 4 different values

  6. Putting values into the array. For the first example, we say the 0 index of this array will hold the value Macaroni.

Declaration

To declare an array, it will look something like this datatype[] arrayName;

datatype is used to specify the type of elements in the array [] specifies that it's an array arrayName specifies the name of the array

Example:

decimal[] bankBalances;

Initializing an Array

The difference between declaring and initializing is when you declare it, it is first just a reference type. After you initialize it using the new keyword, you create a new instance that you can assign values to.

    class Program
    {
        decimal[] bankBalance = new decimal[10];
        bankBalance[0] = 4500.0;
    }

Above, we assigned the first value of the array, index 0, to have the value of 4500. You can also assign values to the array at the time of declaration by following the example below.

decimal[] bankBalance ={2340.0, 4523.69, 3421.0}

or

int [] marks = new int[5] {99, 98, 92, 97, 95}

or

int [] marks = new int[] {99, 98, 92, 97, 95}

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,

decimal johnBalance = bankBalance[3];

Array Examples

    class Food
    {
    string[] food = new string[4];
        food[0] = "Macaroni";
        food[1] = "Pasta";
        food[2] = "Pizza";
        food[3] = "Popcorn";
    }

    class Numbers
    {
        int[] integer2 = new int[5] { 10, 40, 50, 20, 40 };
    }

In the next couple modules, we will work through how to work with data within arrays and show how arrays can be useful. Before moving onto the next module, try creating an array listing some of the topics you have gone over in class so far.

Next: Loops

Last updated