Difference between revisions of "Arrays"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
m (D3: RemovalInability)
 
(14 intermediate revisions by 3 users not shown)
Line 1: Line 1:
 +
===TRC Video===
 +
<youtube>https://www.youtube.com/watch?v=J6E4Neml7Ho</youtube>
 +
 +
https://www.youtube.com/watch?v=J6E4Neml7Ho
  
 
==Understanding arrays==
 
==Understanding arrays==
 
[[File:Arrays.jpg|200px|thumb|right|People queuing.]]
 
[[File:Arrays.jpg|200px|thumb|right|People queuing.]]
 
<p>Arrays are like a queue of people, but person number 0 is the first person in the queue. Imagine it like the picture on the right. As you can see, you know that if you wanted the 3rd person in the queue you would select them something like "queue person 2" and if you wanted the last person in the queue you would say something like "queue person 4" and if you wanted the first person in the queue, you would say "queue person 0". Essentially, instead of starting counting from 1, you start counting from 0.</p>
 
<p>Arrays are like a queue of people, but person number 0 is the first person in the queue. Imagine it like the picture on the right. As you can see, you know that if you wanted the 3rd person in the queue you would select them something like "queue person 2" and if you wanted the last person in the queue you would say something like "queue person 4" and if you wanted the first person in the queue, you would say "queue person 0". Essentially, instead of starting counting from 1, you start counting from 0.</p>
<p>You should also remember that it is possible to create an array within an array. Think of it as a queue, and in each queue is another queue. These special arrays are called Multidimensional Arrays</p>
+
<p>You should also remember that it is possible to create an array within an array. Think of it as a queue, and in each queue is another queue. These special arrays are called [[#MA|Multidimensional Arrays]]</p>
  
 
==Arrays in C#==
 
==Arrays in C#==
Line 31: Line 35:
 
//five
 
//five
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
<p id="MA">To create a '''Multidimensional Array''' add a comer in the square brackets forming the array, for example:</p>
 +
 +
<tabber>
 +
C#=
 +
<syntaxhighlight lang="csharp" line>
 +
int[,] _2DArray = new int[5,5]; // Creates a 2dimensional Array
 +
_2DArray[2,2] = 7; // Accesses item at index X:2 Y:2 and sets it = to 7
 +
 +
Console.WriteLine("{0} AT X:2 Y:2", _2DArray[2,2]);
 +
</syntaxhighlight>
 +
</tabber>
 +
 +
For '''3Dimensional Arrays''' the same process applies, just with another commer, and the same continues for 4, 5, 6... dimensional arrays.
 +
 +
<tabber>
 +
C#=
 +
<syntaxhighlight lang="csharp" line>
 +
int[,,] _3DArray = new int[5,5,5]; // Creates a 3dimensional Array
 +
_3DArray[2,2,2] = 7; // Accesses item at index X:2 Y:2 Z:2 and sets it = to 7
 +
 +
Console.WriteLine("{0} AT X:2 Y:2 Z:2", _2DArray[2,2,2]);
 +
</syntaxhighlight>
 +
</tabber>
 +
 +
To define the items contained in a three dimensional array during runtime, you must use multiple curly braces ({CURLY}) for each dimension however this becomes impractical for any arrays possesing a dimension greater then 2.
 +
 +
<tabber>
 +
C#=
 +
<syntaxhighlight lang="csharp" line>
 +
int[,] _2DArray = new [,] {
 +
    {1, 2, 3, 4, 5}
 +
    {6, 7, 8, 9, 10}
 +
};
 +
 +
// Creates new array with 2 rows and 5 columns
 +
</syntaxhighlight>
 +
</tabber>
  
 
==Arrays & Repetition==
 
==Arrays & Repetition==
Line 63: Line 105:
  
 
==Downsides==
 
==Downsides==
===D1: DataType Suprression===
+
*An array can only be of a single data type
A Given array Can Only contain objects of a given data-type (which is set during initialisation of the array). If a person tries to ignore this, such as in the following case (a TraceBack 'DataType' Error will be produced).
+
*Once declared and initialised, memory is allocated for the whole structure even if it is empty
 +
*Normally they can't be resized once created, ie a Static Data Type.
 +
*Operations such as removing an element or inserting a value in the middle of the array require excessive processing and movement.
  
<tabber>
 
C#=
 
<syntaxhighlight lang="csharp" line>
 
int[] intArray = new int[1]; // Creates new array which holds Integers
 
intArray[0] = "String"; // Attempts to add string to intArray
 
// Producing an error
 
</syntaxhighlight>
 
</tabber>
 
  
However using Object Oriented Programming Concepts (namely Inheritance & Polymorphism) an array can be made to contain Psuedo multiple data types. For example if an interface of type Animal, has two inherited classes Duck & Tiger, both can be added to an array of type Animal with no clipping involved (however if Animal was a class and not an interface, the inherited classes object will be forcefully casted to the class Animal and have some data lossed).
+
For a more detailed examination of these points see: [[Array Downsides extended]]
 
 
<tabber>
 
C#=
 
<syntaxhighlight lang="csharp" line>
 
Interface Animal {
 
    public Output(); // Method
 
 
 
    public int numOfLegs; // instance Value
 
    public String animalName; // instance Value
 
}
 
 
 
class Duck : Animal {
 
    public Duck(int numOfLegs) {
 
        this.numOfLegs = numOfLegs;
 
        this.animalName = "Duck";
 
    }
 
 
 
    public Output() {
 
        Console.WriteLine("{0} has {1} Legs",
 
            this.animalName, this.numOfLegs);
 
    }
 
}
 
 
 
class Tiger : Animal {
 
    public Tiger(int numOfLegs) {
 
        this.numOfLegs = numOfLegs;
 
        this.animalName = "Tiger";
 
    }
 
 
 
    public Output() {
 
        Console.WriteLine("{0} has {1} Legs",
 
            this.animalName, this.numOfLegs);
 
    }
 
}
 
 
 
public Animal[2] animals; // Array Which Can Hold Animals
 
public Tigers[2] tigers; // Array Which Can Hold Tigers
 
public Duck[2] ducks; // Array Which Can Hold Ducks
 
 
 
duck[0] = new Duck(2) // NoError: Adds duck to duck array; Duck Is Duck
 
duck[1] = new Tiger(4); // Error: Adds tiger to duck array; Tiger Isn't Duck
 
 
 
Tiger[0] = new Duck(2) // Error: Adds duck to Tiger array; Duck Isn't Tiger
 
Tiger[1] = new Tiger(4); // NoError: Adds tiger to Tiger array; Tiger Is Tiger
 
 
 
animals[0] = new Tiger(4); // NoError: Adds tiger to animal array; Tiger Is Animal
 
animals[1] = new Duck(2); // NoError: Adds duck to animal array; Duck Is Animal
 
 
 
</syntaxhighlight>
 
</tabber>
 
 
 
Expanding on the example above, to prove no data loss has occured you can attempt to use the built in Output function. to view wether any data loss has occured.
 
 
 
<tabber>
 
C#=
 
<syntaxhighlight lang="csharp" line>
 
animals[0].Output(); // Outputs "Tiger has 4 Legs"
 
animals[1].Output(); // Outputs "Duck has 2 Legs"
 
</syntaxhighlight>
 
</tabber>
 
 
 
===D2: ArrayLength Restriction===
 
An Array is forcefully set to have a given length, and this value cannot be implicitly ignored. for example if an array of length 5, has a value added at index 5 (remember array indexes begin at 0, not 1) an error will be produced.
 
 
 
<tabber>
 
C#=
 
<syntaxhighlight lang="csharp" line>
 
int[] intArray = new int[5]; // creates new array which can hold 5 items of type int
 
 
 
intArray[0] = 5; // Value 1 Set
 
intArray[1] = 4; // Value 2 Set
 
intArray[2] = 3; // Value 3 Set
 
intArray[3] = 2; // Value 4 Set
 
intArray[4] = 1; // Value 5 Set
 
 
 
// Note At this point all values in array have been stored
 
intArray[5] = 0; // Error Produced
 
</syntaxhighlight>
 
</tabber>
 
 
 
Now this length restriction is entirely circumventable (avoidable), and to that end there are 2 option.
 
* Use the builtin Array.Resize() method which automatically resizes a given array
 
** The upside to this is it's short, efficient and reliable as a solution
 
** The downside is that it has to be manually done, and is not an automatic process.
 
* The alternative (which may not seem like much of one) is to use a generic List type instead of arrays
 
** The upside is that a list offers a lot more functionality such as near infinite length (upto the limit of available memory), with a lot less hassle.
 
** The secondary upside is that a List can easily be converted back to an array by using the builtin instance method .ToArray();
 
** The downside to this is more obviously the slight variations posessed by Lists towards arrays, both in syntax & available methods (for example to access the Length of a list you have to use the dot notation with the identifier Size instead of Length).
 
 
 
<tabber>
 
C#=
 
<syntaxhighlight lang="csharp" line>
 
using System.Collections.Generic;
 
 
 
public static void Main(String[] Args) {
 
    int[] intArray = new intArray[10];
 
    int incrementValue = 5;
 
 
 
    for (int X = 0; X < 1000; X++) {
 
        if (intArray.Length == X) {
 
          // If all memoryBlocks in Array full
 
            Array.Resize<int>(intArray, // Lengthen Array
 
                intArray.Length + incrementValue);
 
        }; intArray[X] = X; // Add to IntArray
 
    } // Array.Resize() example;
 
 
 
    List<int> list = new List<int>();
 
 
 
    for (int X = 0; X < 1000; X++) {
 
        list.Add(X); // Adds to List
 
    } // List Based Example
 
}
 
</syntaxhighlight>
 
</tabber>
 
 
 
===D3: RemovalInability===
 
An Array can be used to hold numerous blocks of memory, but because of this they dont offer much in terms of removing values added to an array. There are two ways to remove values added to an array:
 
* Set the value of an entry we wish to remove to Null.
 
** The upside to this is that this is simple and efficient way to mark a given value in an array as empty (as be default all unassigned values in an array are Null).
 
* Alternatively one could just use a List again.
 
** Lists come with the builtIn Pop method, which can remove any value in a list.
 
 
 
 
 
<tabber>
 
C#=
 
<syntaxhighlight lang="csharp" line>
 
using System.Collections.Generic;
 
 
 
public static void Output(String[] array) {
 
    Console.WriteLine(String.join(" ", array));
 
}
 
 
 
public static void Main(String[] Args) {
 
    String[] sArray = new String[] {"One", "Two", "Three", "Four", "Five"};
 
    List<String> sList = new List<String>("One", "Two", "Three", "Four", "Five");
 
 
 
    sArray[2] = Null; // Removes "Three"
 
    sList.Pop(2); // Removes "Three"
 
 
 
    Output(sArray); // Outputs "One Two  Four Five" // Notice the gap after Two
 
    Output(sList); // Outputs "One Two Four Five" // Notice no gap after Two
 
}
 
</syntaxhighlight>
 
</tabber>
 

Latest revision as of 08:21, 23 August 2023

TRC Video

https://www.youtube.com/watch?v=J6E4Neml7Ho

Understanding arrays

People queuing.

Arrays are like a queue of people, but person number 0 is the first person in the queue. Imagine it like the picture on the right. As you can see, you know that if you wanted the 3rd person in the queue you would select them something like "queue person 2" and if you wanted the last person in the queue you would say something like "queue person 4" and if you wanted the first person in the queue, you would say "queue person 0". Essentially, instead of starting counting from 1, you start counting from 0.

You should also remember that it is possible to create an array within an array. Think of it as a queue, and in each queue is another queue. These special arrays are called Multidimensional Arrays

Arrays in C#

There are several ways of declaring arrays in C#. There are several ways shown below:

Creates an empty array that will return integers.

int[] arrayname; // Allocates Array to Memory But Doesn't Initalize It

Creates an empty array that will return integers, but it's size is 10. (10 people in a queue).

arraynumbers = new int[10]; // Allocates &amp Initalises

Creates an array with values for each number in the queue.

int[] numbers = {1, 2, 3, 4, 5};

Don't forget that it can be any data type.

string[] strings = {"one", "two", "three", "four", "five"};

To get something from an array, you can simply do the same as I explained before.

1 string[] strings = {"one", "two", "three", "four", "five"}; //Declares strings as an array of strings.
2 Console.WriteLine(strings[0]); //Writes the first thing in the array
3 Console.WriteLine(strings[2]); //Writes the third thing in the array
4 Console.WriteLine(strings[4]); //Writes the fifth thing in the array
5 //Output:
6 //one
7 //three
8 //five

To create a Multidimensional Array add a comer in the square brackets forming the array, for example:

1 int[,] _2DArray = new int[5,5]; // Creates a 2dimensional Array
2 _2DArray[2,2] = 7; // Accesses item at index X:2 Y:2 and sets it = to 7
3 
4 Console.WriteLine("{0} AT X:2 Y:2", _2DArray[2,2]);

For 3Dimensional Arrays the same process applies, just with another commer, and the same continues for 4, 5, 6... dimensional arrays.

1 int[,,] _3DArray = new int[5,5,5]; // Creates a 3dimensional Array
2 _3DArray[2,2,2] = 7; // Accesses item at index X:2 Y:2 Z:2 and sets it = to 7
3 
4 Console.WriteLine("{0} AT X:2 Y:2 Z:2", _2DArray[2,2,2]);

To define the items contained in a three dimensional array during runtime, you must use multiple curly braces ({CURLY}) for each dimension however this becomes impractical for any arrays possesing a dimension greater then 2.

1 int[,] _2DArray = new [,] {
2     {1, 2, 3, 4, 5}
3     {6, 7, 8, 9, 10}
4 }; 
5 
6 // Creates new array with 2 rows and 5 columns

Arrays & Repetition

A for loop can be used to access every element within a array, this could be to read or write from the array:

1  int[] NumList = new int[1000];
2  Random RanNum = new Random();
3  for (int i = 0; i < 1000; i++) 
4  {
5       NumList[i] = RanNum.Next(1,10000);
6  }

This declares an array of 1000 integers. The for loop will cycle from 0 to the thousandth item and each cycle will add a random number into that element of the array. You could use a for loop to read the list also:

1  for (int i = 0; i < 1000; i++) 
2  {
3       Console.WriteLine(NumList[i]);
4  }

If you only wish to read from the array you could also use a foreach loop:

1  foreach (int value in NumList) 
2  {
3       Console.WriteLine(value);
4  }

Downsides

  • An array can only be of a single data type
  • Once declared and initialised, memory is allocated for the whole structure even if it is empty
  • Normally they can't be resized once created, ie a Static Data Type.
  • Operations such as removing an element or inserting a value in the middle of the array require excessive processing and movement.


For a more detailed examination of these points see: Array Downsides extended