# How to get the number of elements of an Array in Arduino

It is common to use arrays as part of the code we want to upload to Arduino. There are chances at some point you have declared an array without explicitly defining its size, but instead, you opt to populate the array right away like in the following example:

`int digitalPins[] = {2, 3, 4, 5, 6};`

At some point in your code, you want to run logic using each element of the array. Hence, you think of using a `for` loop. Using a loop to iterate over each element of an array means we should know the total number of elements of the array, such as the following example:

```for (int i = 0; i < totalDigitalPins; i++) {
// apply logic to digitalPins[i]
}```

You want to determine the number of elements of an array dynamically to assign get the value of `totalDigitalPins`. The first thing you find in the Arduino documentation is using sizeOf() utility function without fully understanding the definition of what it does.

```int digitalPins[] = {2, 3, 4, 5, 6};
int totalDigitalPins = sizeOf(digitalPins);

for (int i = 0; i < totalDigitalPins; i++) {
// apply logic to digitalPins[i]
}```

Unfortunately, you quickly realize using `sizeOf `utility function doesn’t truly get the number of elements of the array.

In this article, I’m going to explain in detail how to find the number of elements of an array, talk about reasons why there is not a built-in function that gets the length of an array, share some recommendations as well as share my experience of why I needed to a way to dynamically get the size of the array.

## How do you find the number of elements of an array in Arduino?

Arduino code is written in C++, and the formula to get the number of elements in an array in C++ is to get that size of the array in size divided by the size of a single element of the array.

In our initial example, we had declared an array called `digitalPins`. Hence, if we apply this formula to get the value of `totalDigitalPins`, the code would result like this:

```int digitalPins[] = {2, 3, 4, 5, 6};
int totalDigitalPins = sizeOf(digitalPins) / sizeOf(digitalPins);

for (int i = 0; i < totalDigitalPins; i++) {
// apply logic to digitalPins[i]
}```

In that way, we can iterate through each element of the array when using a `for` loop.

### Explanation

In Arduino, we can determine how many bytes are used in memory whenever we declare a variable using a data type using the `sizeOf` function.

```bool bo;
boolean boo;
byte byt;
char cha;
double doubl;
float floa;
int in;
long lon;
short shor;
size_t size_;

void setup() {
Serial.begin(9600);

Serial.println("total  BYTES a bool Data Type");
Serial.println(sizeof(bo));

Serial.println("total  BYTES a boolean Data Type");
Serial.println(sizeof(boo));

Serial.println("total  BYTES of a byte Data Type");
Serial.println(sizeof(byt));

Serial.println("total  BYTES of a char Data Type");
Serial.println(sizeof(cha));

Serial.println("total  BYTES of a double Data Type");
Serial.println(sizeof(doubl));

Serial.println("total  BYTES of a float Data Type");
Serial.println(sizeof(floa));

Serial.println("total  BYTES of an int Data Type");
Serial.println(sizeof(in));

Serial.println("total  BYTES long Data Type");
Serial.println(sizeof(lon));

Serial.println("total  BYTES short Data Type");
Serial.println(sizeof(shor));

Serial.println("total  BYTES size_t Data Type");
Serial.println(sizeof(size_));
}```

If you run the previous logic in Arduino while you have the Serial Monitor open to read the logs using the Serial.println() function, you will soon understand how much space these data types are occupying in memory. For example, the `bool`, `boolean`, `byte`, and `char` data types use one byte, while `double`, `float`, and `long` data types use 4 bytes in Arduino UNO R3.

In a similar way, we can do this with an array.

```int digitalPins[] = {2, 3, 4, 5, 6};

void setup() {
Serial.begin(9600);

Serial.println("total  BYTES a digitalPins array");
Serial.println(sizeof(digitalPins));
}```

In this case, the bytes used in `digitalPins` with 5 elements inside the array is 10.

If you add more elements or remove more elements, the bytes occupied on this array will vary. However, what if we have another array with the same number of elements but with a different data type, let’s say the `char` data type. Will it use the same number of bytes than `digitalPins`?

```char letters[] = {'a', 'r', 'd', 'u', 'c'};

void setup() {
Serial.begin(9600);

Serial.println("total  BYTES a letters array");
Serial.println(sizeof(letters));
}```

Depending on which data types are used in the two arrays, the answer could be either yes or no. In this case, the answer is no.

Why is this happening?

Remember, each data type can use a different number of bytes. As we previously saw, an `int` data type uses two bytes, and a `char` data type uses one byte.

Hence, to calculate the number of bytes in an array, you need to determine the number of elements of that array times the byte size of the data type used in the array.

Therefore, in the case of `digitalPins`, we know it has 5 elements and its data type is `int`, and `int` data type uses 2 bytes. If we multiply these two numbers, we get 10.

`digitalPins `bytes = 5 x 2 = 10

If we do the same for `letters` array, we get the following calculation:

`letters` bytes = 5 x 1 = 5

However, we know `sizeOf `already gets the bytes of any variable, and we wouldn’t necessarily have to calculate the size of bytes of an array.

```int digitalPins[] = {2, 3, 4, 5, 6};
char letters[] = {'a', 'r', 'd', 'u', 'c'};

void setup() {
Serial.begin(9600);

Serial.println(sizeof(digitalPins));
Serial.println(sizeof(letters));
}```

However, using this information, we can determine the number of elements of an array in case you want to dynamically get that value.

```char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int totalLetters = sizeOf(letters) / sizeOf(letters);```

## Why isn’t there a built-in function that gets the length of an array in Arduino?

If you happen to be a software engineer, software developer, or programmer, you probably have worked with other programming languages such as JavaScript, PHP, C#, Java, etc. Similar to C/C++, those programming languages also use arrays.

However, these languages have built-in methods or properties to get the length of an array. For instance, in Javascript, getting the number of elements of an array would like this:

```const myArray = [1,2,3,4,5,6,7];
const totalElementsOfArray = myArray.length;```

Why isn’t there a built-in function to C/C++ to get the length of an array?

A lot of it has to do with how these two programming languages were used in a time were computers had limited resources. If you think about it, Arduino is not a powerful as a phone or a computer, and it also has limitations when it comes to memory storage. Adding built-in functions means using some of that extra space that could be used on writing the logic to use in the Arduino.

Another good reason is C/C++ contrary to higher-level programming languages like JavaScript, you can’t append elements to an array. Hence, if you create an array in JavaScript without declaring the number of elements that the array can have, you can append more elements to the array, and be constraint by an array size. On the other hand, in C/C++ there is no way to add more elements to a fixed-sized array.

## Recommendation

The general recommendation is to define the size of the array prior to declaring the array. In that way, you avoid trying to calculate the number of elements of an array.

```int arraySize = 5;
int digitalPins[arraySize] = {2, 3, 4, 5, 6};
char letters[arraySize] = {'a', 'r', 'd', 'u', 'c'};```

## Use Cases

The other day, I was working on building a simple circuit to connect multiple LEDs using multiple Arduino pins. The code consisted of defining an array of led pins and using a `for` loop to configure all the digital pins of Arduino in `OUTPUT` mode to send HIGH or LOW signals from those Arduino pins to turn on and off multiple LED lights. The code was this:

```/*
Connect Multiple LEDs using Multiple Arduino Pins.
For more guides and tutorials: https://www.thecircuitmaker.com
*/
// set up array variable to store the all pin number that will turn on the LEDs
int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int totalPins = sizeof(ledPins) / sizeof(int);
// 1 second delay
int delayTime = 1000;
void setup() {
// configure the LED pins to behave as OUTPUT mode to send HIGH or LOW signals
for (int i = 0; i < totalPins; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
}
for (int i = 0; i < totalPins; i++) {
// turn on the LED
digitalWrite(ledPins[i], HIGH);
}
// wait for 1 second
delay(delayTime);
for (int i = 0; i < totalPins; i++) {
// turn off the LED
digitalWrite(ledPins[i], LOW);
}
// wait for one second
delay(delayTime);
}
for (int i = 0; i < totalPins; i++) {
// turn on the LED
digitalWrite(ledPins[i], HIGH);
// wait for 1 second
delay(delayTime);
// turn off the LED
digitalWrite(ledPins[i], LOW);
// wait for one second
delay(delayTime);
}
}
// select random pin number
int randomIndex = random(totalPins);
int pinSelected = ledPins[randomIndex];

// turn on the LED
digitalWrite(pinSelected, HIGH);
// wait for 1 second
delay(delayTime);
// turn off the LED
digitalWrite(pinSelected, LOW);
// wait for one second
delay(delayTime);
}```

Notice how I’m using `totalPins` or the number of elements of the `ledPins` to run logic to blink the LEDs.

## Conclusion

In this article, you learned how to calculate the number of elements of an array in C++, the programming language used in Arduino. While there is not a built-in function that does calculate the length of an array, we can still determine the total number of elements of the array by using `sizeOf`. However, it is recommended to define in a variable the size of the array to avoid doing any additional calculations.