Friday, 1 May 2015

Array: 1 Dimensional

An array can be though of as a sequential list of a particular type of object in which each object is refereed to by a zero based index. Zero based simply means that the first elements address is 0. One can think of it as a single row or column of a table.

For example if we created an array of 10 random numbers it would look something like this

Index 0 1 2 3 4 5 6 7 8 9
value A B C D E F G H I J

The syntax to declare an array is generally something along the lines of

    
    char[] myArrayOfChars = new char[10]
myArrayOfChars[0] = 'A';
       myArrayOfChars[1] = 'B';
      myArrayOfChars[2] = 'C';
      myArrayOfChars[3] = 'D';
      myArrayOfChars[4] = 'E';
      myArrayOfChars[5] = 'F';
      myArrayOfChars[6] = 'G';
      myArrayOfChars[7] = 'H';
      myArrayOfChars[8] = 'I';
      myArrayOfChars[9] = 'J';


Above we define an array called myArrayOfChars and we specify that it can only contain the type char and it only has space enough for ten of them.

Enough talk, let's create a console application to demonstrate what we're talking about.

Let's start by creating our application
dotnet new console -n oneDimArray --use-program-main

with our application created let's now open it up in ms code
code oneDimArray 


Paste in the following code

    
    namespace oneDimArray;
    class Program
    {
        static void Main(string[] args)
        {
            char[] myArrayOfChars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
       
            for(int i = 0; i < myArrayOfChars.Length; i++)
                Console.WriteLine($"i={i} v={myArrayOfChars[i]}; ");
        }
    }


In the above we define our array a little differently,  here rather than defining our array size and manually specifying the value at each index we do it all in one swoop. If we run our application we'll see the following.


We've iterated over each our our elements and outputted it's value. You may be wondering ok, but what would happen if we tried to print out myArrayOfChars[10], since we only have 0 to 9 defined, we'll let's find out. Let's add the following after our for loop.

    
    Console.WriteLine($"i={10} v={myArrayOfChars[10]}; ");


Now let's run our application with "dotnet run" 

we should get the same output as before but with an exception thrown at the end 

Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at oneDimArray.Program.Main(String[] args) in D:\learn\oneDimArray\Program.cs:line 14

this is our first Runtime exception, that is to say it's not a syntax error, the code is written correctly, however since there is no 10th "Spot" in our array we get an IndexOutOfRange Exception.