Academic Program

Arrays

​Arrays

Arrays are variables that can store many items of the same type. The individual items known as elements, are stored sequentially and are uniquely identified by the array index (sometimes called a subscript).

  • May contain any number of elements
  • Elements must be of the same type
  • The index is zero based
  • Array size (number of elements) must be specified at declaration

How to Create an Array

Syntax

type arrayName [size];

  • size refers to the number of elements
  • size must be a constant integer

Example

 
1
2
 
int a[10];    // An array that can hold 10 integers
char s[25];   // An array that can hold 25 characters
How to Initialize an Array at Declaration
Syntax

type arrayName [size] = {item1, …, itemn};

The items must all match the type of the array
Example
 
1
2
 
int a[5] = {10, 20, 30, 40, 50};
char b[5] = {'a', 'b', 'c', 'd', 'e'};
How to Use an Array
Arrays are accessed like variables, but with an index:
Syntax

arrayName [index]

  • index may be a variable or a constant
  • The first element in the array has an index of 0
  • C does not provide any bounds checking
Example
1
2
3
4
5
6
int i, a[10];   //An array that can hold 10 integers
 
for(i = 0; i < 10; i++) {
  a[i] = 0;     //Initialize all array elements to 0
}
a[4] = 42;      //Set fifth element to 42
Creating Multidimensional Arrays
Add additional dimensions to an array declaration:
Syntax

type arrayName [size1]…[sizen];

  • Arrays may have any number of dimensions
  • Three dimensions tend to be the largest used in common practice
Example
1
2
int a[10][10];        //10x10 array for 100 integers
float b[10][10][10];  //10x10x10 array for 1000 floats
Initializing Multidimensional Arrays at Declaration
Syntax

type arrayName [size0]…[sizen] =
{{item,…,item},
.
.
.
{item,…,item}};

Example
1
2
3
4
5
char a[3][3] = {{'X', 'O', 'X'},
                {'O', 'O', 'X'},
                {'X', 'X', 'O'}};
 
int b[2][2][2] = {{{0, 1},{2, 3}},{{4, 5},{6, 7}}};
Visualizing 2-Dimensional Arrays
2DArrays.png
Visualizing 3-Dimensional Arrays
3DArrays.png
Array Processing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**************************************************
* Print out 0 to 90 in increments of 10
**************************************************/
int main(void)
{
    int i = 0;
    int a[10] = {0,1,2,3,4,5,6,7,8,9};
 
    while (i < 10)
    {
        a[i] *= 10;
        printf("%d\n", a[i]);
        i++;
    }
 
    while (1);
}
  • Arrays are frequently processed as part of a loop since the same operation needs to be performed on each element
  • Operations might include
    • Sending strings of characters to or reading strings of characters from a UART
    • Performing a mathematical transform on an array of floating point numbers (think digital filters)
  • The loop count variable will often be used as the array index itself or in conjunction with the array index