Arrays and Loops
Arrays and Loops
In Arduino programming, arrays and loops are essential tools for efficient and organized coding.
Arrays:
An array is a collection of variables stored under a single name, where each element is accessible using
an index. It allows storing multiple values of the same type in a single data structure, making it easier to
manage related data.
int value = myArray[2]; // Accesses the third element (30 in this case)
Loops with Arrays:
Loops, such as for and while, are often used to iterate through arrays, enabling efficient handling of
multiple elements.
void setup() {
Serial.begin(9600); // Start serial communication
for (int i = 0; i < 5; i++) { // Loop through the array
Serial.println(myArray[i]); // Print each element
}
Indexing in Arrays:
• Index starts at 0. For an array of size N, the indices range from 0 to N-1.
• Attempting to access an index outside this range (e.g., myArray[5] in the above example) may
lead to undefined behavior.
• The index can be dynamically controlled using variables, often updated within loops.
By combining arrays and loops, Arduino programs can efficiently manage and manipulate data, whether
controlling multiple LEDs, reading multiple sensors, or processing data in bulk.
The for loop is a control structure used to repeatedly execute a block of code for a specified number of
iterations. It is particularly useful when you know in advance how many times you want the loop to run.
6. Condition: Evaluates before each iteration. The loop continues as long as this condition is true.
7. Update: Adjusts the loop variable after each iteration, typically with an increment (++) or
decrement (--).
void setup() {
Serial.begin(9600);
for (int i = 0; i < 5; i++) { // Loops from 0 to 4
Serial.println(i); // Prints the current value of i
}
Output:
4
Common Use Cases
4. void setup() {
5. Serial.begin(9600);
6. for (int i = 10; i >= 0; i--) { // Loops from 10 to 0
7. Serial.println(i);
8. delay(1000); // 1-second delay
9. }
10. }
11.
• Efficiency: Great for managing repetitive tasks like iterating over arrays.
Usage
• Ensure the condition avoids infinite loops (e.g., for (;;) runs forever).
• Avoid accessing out-of-bounds indices in arrays (e.g., myArray[i] where i exceeds array size).
• You can nest for loops for multi-dimensional operations but use them sparingly to maintain
readability.