Arrays

An array is a consecutive group of memory locations that are of the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array.

Syntax:

type arrayName [ arraySize ] ;

Example 1: Declaring an Array and using a Loop to Initialize the Array’s Elements

int n[ 10 ] ; // n is an array of 10 integers

void setup ()
{
}

void loop ()
{
for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0
{
n[ i ] = 0; // set element at location i to 0
Serial.print (i) ;
Serial.print (‘\r’) ;
}
for ( int j = 0; j < 10; ++j ) // output each array element's value
{
Serial.print (n[j]) ;
Serial.print (‘\r’) ;
}
}

Example 2: Initializing an Array in a Declaration with an Initializer List

// n is an array of 10 integers
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ;
void setup ()
{
}
void loop ()
{
for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0
{
Serial.print (i) ;
Serial.print (‘\r’) ;
}
for ( int j = 0; j < 10; ++j ) // output each array element's value
{
Serial.print (n[j]) ;
Serial.print (‘\r’) ;
}
}

 

Multi-dimensional Arrays

Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of information arranged in rows and columns.

Following are the key features of multidimensional arrays:

  • To identify a particular table element, we must specify two subscripts.
  • By convention, the first identifies the element’s row and the second identifies the element’s column.
  • Arrays that require two subscripts to identify a particular element are called two-dimensional arrays or 2-D arrays.
  • Arrays with two or more dimensions are known as multidimensional arrays and can have more than two dimensions.

Example: Defining Array

void printArray ( const int [][ 3 ] ); // prototype const int rows = 2;

const int columns = 3;
int array1[ rows ][ columns ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ rows ][ columns ] = { 1, 2, 3, 4, 5 };
int array3[ rows ][ columns ] = { { 1, 2 }, { 4 } };

void setup ()
{
}
void loop ()
{
Serial.print ("Values in array1 by row are: ") ; Serial.print (“\r” ) ;
printArray(array1) ;
Serial.print ("Values in array2 by row are: ") ; Serial.print (“\r” ) ;
printArray(array2) ;
Serial.print ("Values in array3 by row are: ") ; Serial.print (“\r” ) ;
printArray(array3) ;
}
// output array with two rows and three columns void printArray( const int a[][ columns ] )
{
// loop through array's rows
for ( int i = 0; i < rows; ++i )
{
// loop through columns of current row for ( int j = 0; j < columns; ++j )
Serial.print (a[ i ][ j ] );
Serial.print (“\r” ) ; // start new line of output
} // end outer for
} // end function printArray

Result

Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0

 

 

Advertisements