Rabu, 21 Oktober 2015

Array C++

What is Array?? (C++ style)

Array is a variable that store a bunch of data that have the same type. Each data to occupy the different memory locations or addresses and further called with array element. These array element  can be accessed through index from inside it. But, It is very important to take a look that in array index always start from 0, not 1. Below here is a picture how array works.

1st  Value
2nd Value
….
Nth Value
   Array Element Value
1st Address
2nd Address
Nth Address
   Array Element Address
0
1
N
   Array Element Index

To declare an array in C++ , we must use bracket [ ]. The common form of the declaration is below here:

data_type array_name[element_amount];

As example, if we want to declare an array (for example, with the name ARRAY) which have 25 elements with data type int, therefore the declaration form is looks like the one below:

int ARRAY[25];

Memory room that's required to declare this array is about 100 byte, that's comes from 25 x 4 (4 is size from data type int). The way which is used to access the element is with write the index. For example we want to take a value that is in the 10th element and store the value into a variable with type int too (example, X), then we need to write the code like the below:

X=ARRAY[9]

Why 9, not 10? Remember, index array always start from 0 so that to access the 10th element, then the index we need is 10 - 1, that is 9. 

Tidak ada komentar:

Posting Komentar