arrays are actually quite simple. each language has their own way of making them, but they are all used the same way. an array is the most basic container. a container is something that holds sets of data. in c++, which is strongly typed (meaning that if you make an int variable, it cant be used as a float variable). as such, if you make an array of type
char
then it will only hold char values. lets look at some actual code now. first, you have to declare your array (for this mini tutorial we will use int, but you could really use it with any datatype (ie bool, float, double, char, string):
int myarray[10]
lets take a look at this:
int myarray[10]
this declares an array called myarray of type int. what the [10] means is that it can hold 10 values. you can now fill it with values like this:
1 2 3 4 5
|
myarray[0] = 1;
myarray[1] = 4;
myarray[2] = 745;
//...
myarray[9] = 74;
|
notice how i started at zero? that is because the first "cell" (ie myarray[0]) starts at zero. so the second cell is myarray[1]. we can also set it to the value of other variables:
1 2
|
int i = 10;
myarray[4] = i;
|
now lets say you wanted to give it a predetermined set of values:
|
int myarray[] = {10, 4, 5, 7};
|
this might seem strange at first. lets take a look:
each element is comma seperated. this puts each in its own cell. ie:
myarray[0] = 10
myarray[1] = 4
myarray[2] = 5
myarray[3] = 7
also notice how there is no size in the [] of myarray[] = {...}. that is because if you give it default values (ie {10, 4, 5, 7}) then its size is the number of elements in the list. in this case its 4 (because 10 is the first element, 4 is the second, 5 is the third, and 7 is the fourth). if you want you can include a size and a default value list. if the size is greater than the number of elements in the list, then the remaining free spaces are filled with zereos. ie
int myarray[10] = {9, 6, 5};
. the remaining 7 cells will be filled with 0's. if the size is smaller than the number of the elements in the list, then it makes the size the same as the number of elements in the default value list.