<http://lib.cnfolio.com/ENG421DataArrays>
Introduction to Algorithms and Programming

Introduction to arrays



Concept of an array


Programs often use a list of variables which are of the same data type and share a common list name.

For example, below is a problem which needs 3 variables of the same float data type and using a common list name, month.

Variables to store the input values:
float month1, month2, month3;

Sample monthly revenue input values:
5100.50  5200.04  4992.37


Variables to store the output values:
float average, total;

Sample output display:
The average monthly revenue is 5097.64
The total revenue earned is 15292.91



The problem becomes more awkward when the requirement changes to 12 variables of the same float data type and a common list name, month.

Variables to store the input values:
float month1, month2, month3, month4, month5, month6;
float month7, month8, month9, month10, month11, month12;


Variables to store the output values:
float average, total;



An array is used to manage a set of variables that all have the same data type.

An array allows variables to be easily controlled using iteration.

An array to store the input values:
float months[ 12 ] = { 0 };

months[0] months[1] months[2] months[3] months[4] months[5] months[6] months[7] months[8] months[9] months[10] months[11]
0 0 0 0 0 0 0 0 0 0 0 0




Description of an array


months[0] months[1] months[2] months[3] months[4] months[5] months[6] months[7] months[8] months[9] months[10] months[11]
0 0 0 0 0 0 0 0 0 0 0 0

float months[ 12 ] = { 0 };

An array is used to manage a set of variables that all have the same data type.





An array is suited for use with iterations (loops)


months[0] months[1] months[2] months[3] months[4] months[5] months[6] months[7] months[8] months[9] months[10] months[11]
0 0 0 0 0 0 0 0 0 0 0 0

float months[ 12 ] = { 0 };

An array allows variables to be easily controlled using iteration.





The array length is the not the same as an element index.




3 different ways to declare and initialise arrays



The array length can be automatically determined by the number of values in the initialization list.

float months[] = { 5100.50, 5200.04, 4992.37, 3721.18, 3299.68, 4229.02, 3510.54, 6920.74, 4291.57, 3964.92, 3719.98, 4323.12 };



Every element in the array can be initialized to the same value.

float months[ 12 ] = { 0 };



Declare an array without any initialisation values.

float months[ 12 ];





Arrays are contiguous in program memory


An array is stored as a contiguous sequence in program memory.

Amount of memory used by an array = ( array length ) x ( memory for array data type )





Conceptually, we think of a two dimensional array as a table:





However, arrays are stored sequentially in program memory: