What is an Array?
An array is simply a place to store an amount of items, that can be used later easily.
Defining a fixed Array
First, you must specify the type of items to store in your array, lets say for example you want to store a list of integers. Then, the number of items (integers) you want to store.
The following code snippet creates an array of 4 integers.
int[] myFirstIntArray = new int[4];
Storing items in your array
In C#, an array index starts at 0, and ends at the array length minus one.
To store data in a predefined array, the basic way, just set the value of each item in your array, using the equal sign!
Let's consider our previous example. we want to store in it the following information:
- my age.
- my birth-year.
- my birth-month.
- my birth-day.
myFirstIntArray[0] = 19 ; //19 years old myFirstIntArray[1] = 1993 ; myFirstIntArray[2] = 7 ; //July myFirstIntArray[3] = 21 ;
Of course, you may need to store a big amount of items and you're not gonna put them all one by one, so in this case we usually use the Loops.
A good example: Let's say we want to get the list of the first 100 prime numbers. Here we are going to use a do-While loop.
int[] primeNbrs = new int[100]; int number = 2; int index=0; do { int i = 2; while ((i < number) && (number % i != 0)) i++; if (i == number) { primeNbrs[index] = number; index++; } number++; } while (index < 100);If you have any questions, COMMENT!