Arrays

aka Array Data Structure.

 

Sequential collection of same data type variables.

 

Declared by use of [square brackets]:

 

Syntax:    data type array Name[array size] ;

 

Values in the array are referred to as elements, and ALWAYS START FROM ZERO!

 

int myArray[10] ;  //declares an array called myArray that can contains 10 elements of the int data type

 

Defined by assigning comma separated values, within { curly braces }

 

int myArray[10] = {2, 3, 7, 12, 14, 17, 42, 63, 70, 99} ;

The number of elements defined must exact match the number of elements declared.

 

Alternatively, an array can be defined without having to specify the number of elements, in which case the compiler will automatically size the array upon definition of the elements:

 

int myArray[] = {3, 13, 1, 56, 33} ; // array will be automatically sized to hold the number of elements defined

 

 

Array index

Integer pointer for each element of the array. An array sized with 10 elements (e.g. int arr[10] ;) has 10 index pointers for each element starting from 0, progressing to 9.

 

Single array elements can be defined by assigning a value to the required index number of the element (starting from zero) using the square brackets [ ], aka subscript:

 

myArray[6] = 21 ; //assigns the value 21 to the 7th element

 

Similarly, elements can be accessed by specifying the required index number of the element (starting from zero):

 

int myVar = myArray[4] ; //access the 5th element of myArray and assigns it to myVar

 

Compile & Run:

Uninitialised values:
2686916
1985711317
-1992624055
-2
1985614178 

Initialised values:
9
6
8
2
5

Array values initialised at declaration:
5
9
2
5
8

Leave a Reply