5.0 Array
5.0 Array
Array
• A data structure used to store a collection of data of the same data
type that can be individually referenced by adding an index to a
unique identifier.
• Once defined, the size of an array is fixed and cannot increase to
accommodate more elements.
• The array indices start with 0. Meaning x[0] is the first element stored
at index 0.
• If the size of an array is n, the last element is stored at index (n-1). In
this example, x[5] is the last element.
Array
x0=0; x[0]=0;
x1=1; x[1]=1;
x2=2; x[2]=2;
x3=3; x[3]=3;
x4=4; x[4]=4;
x5=5; for(count=0; count<5; count++) { x[5]=5;
cout<<x[count];
}
Array Declaration & Initialization
• Syntax: dataType arrayName [ arraySize ];
dataType arrayName [ arraySize ]={ elem1, elem2, elem3..}
• The arraySize must be an integer constant greater than zero and type can be any valid
C++ data type.
int intArray[5];
int intArray[5] = {1, 2, 3, 4, 5};
int intArray[ ] = {1, 2, 3, 4, 5};
// intArray is an array variable which stores 5 integer values
// The number of values between braces { } can not be larger than the number of
// elements that we declare for the array between square brackets [ ]
Accessing Array
• An element is accessed by indexing the array name.
• Place the index of the element within square brackets after the name
of the array.