Arrays

Instead of creating a single integer variable, we can create an array of integer, a collection of the several independent values inside one container. Here is a example of declaring an array of 5 integers in some language :

// C
int myArray[5] = {1, 3, 5, 7, 9};

// Swift
var myArray = [1, 3, 5, 7, 9]

// Ruby
myArray = [1, 3, 5, 7, 9]

// C#
int[] myArray = {1, 3, 5, 7, 9}

While the syntax to create an array is different, but one thing is very common is to see square brackets ('[ ]') being used somewhere in the syntax. Of course array can be used for any data types and have any value.

Each array you make has a name, but each individual value inside that array doesn't have a name. We still can access each element inside array, because they have an index. Index in array always starts with 0, so element in the first position in array will have index value of 0.

var myArray = [1, 3, 5, 7, 9]

print myArray[2] //it will print 5

In example above, we try to print number in index value of 2, that means a number in third position in array. That's why it showing 5. We called it with the name of array and followed by index value we want to access.

Another example :

int[] myArray = {1, 3, 5, 7, 9}

int number = myArray[4]   //number now have value of 9

Yes, you can assigning element in array to variable using the same way.

Collections

Array is classic way to hold organized multiple data item in your program, but they not the only way.

While each of these good in different thing, they basically have the same idea with Array, so we called them Collections.

results matching ""

    No results matching ""