The Arduino For Loop

The Arduino for loop is one of those bread-and butter functions that you will use all the time in your code. Microcontrollers are good at repetitive tasks but instead writing out the same code many times, the for-loop repeats a section of code a specific number of times.

Where to use for-loops

You can use for loops anywhere inside a function, so you can use them in the standard Arduino setup(), and loop() functions, and within your own functions.

The following example shows a for-loop that loops round printing the numbers 0 to 9. It is placed into the setup() function since you only want to perform the for-loop action one time - otherwise if you place it within the loop() function it repeatedly outputs information - making you head spin (try it and see)!

Copy the code into the Arduino IDE. Compile and run the program. Start the serial monitor to see the output.

This code shows an Arduino for loop example with the for loop itself within the setup() function. This is not the place you should normally use a for loop (you can though) - its only here to stop multiple output.

void setup (void) {


   Serial.println("Arduino for loop");
   for (int i=0; i<10; i++) Serial.println(i);

void loop(void) {

How the Arduino for loop works

The Arduino for loop provides a mechanism to repeat a section of code depending on the value of a variable. So you set the initial value of the variable, the condition to exit the loop (testing the variable), and the action on the variable each time around the loop.

Initialiser section: The initial value of the control variable.
Condition Section: The condition to stop the loop.
Iterator Section:
The loop variable action (increment or decrement).

These three elements are parameters to the for loop and are separated by semicolons:

for ( <initialiser code> ; <condition test expression> ; <iterator expression> ) {
   <body code>

Arduino Loop Counter Control Variable

The other important point about for-loops is that they need a loop control variable - in the example this is the variable i. This is used as a loop counter and is used to decide when to exit the loop.

The code shown previously is the standard way to write a for-loop in which the loop variable starts at zero and is incremented 10 times.
for (int i=0; i<10; i++) Serial.println(i);
Note: The value of 'i' goes from 0 to 9 which is 10 times round the loop.
Note: The value of 'i' after the loop is completed is 10. A little bit counter intuitive, but to stay in the loop, 'i' can only range from 0 to 9, at 10 it exits. You can use the 'i' variable in later code as well.

Parameters of the Arduino for loop


int i = 0;

First of all the variable 'i' is created (if it does not already exist) and set to zero.

This section of the for-loop is only executed once at the beginning.


i < 10;

Next the loop variable is tested. Here, if it is smaller than 10 then carry on - otherwise the loop is exited.

This is executed every time around the loop.



The loop control variable (loop counter) is increased by one.

This is executed every time around the loop.

Arduino For loop Output

So the for-loop executes the code "Serial.print(i)" 10 times with value of 'i' going through 0 to 9.

And this is the output:

Arduino for loop
To see why you start the control variable from zero you should look at the section on arrays and for-loops.

For a different way of doing a similar action you could allow the control variable to change from 1 through 10.
for (int i=1; i<=10 ; i++) Serial.println(i);
This would print out 1 through 10. It is still 10 iterations but starting from 1.

Note: Here 'i' ranges from 1 to 10 i.e. 10 times round the loop.

At the end of the loop code (outside curly braces) the value of 'i' will be 11, because when 'i' reaches 11 the statement 'i<=10' is false so the loop is exited.

Note: This time at the end of the loop, 'i' has the value 11.

Arduino for-loop body code

The body of the for loop can either be a single statement of a block of code between curly braces. So you could write the loop as follows:

void setup (void) {


   Serial.println("Arduino for loop");
   for (int i=0; i<7; i++) {
      Serial.print("i is : ");

void loop(void) {

Notice how there are two statements - ending in semicolons and both are enclosed by curly braces. Compare this to the previous example that used only one statement ending in a semi-colon.

In this case the output is:
Arduino for loop
i is : 0
i is : 1
i is : 2
i is : 3
i is : 4
i is : 5
i is : 6
i is : 7

Test Yourself

Q: Here's a question for you. What is the value of i after the loop has finished executing?

The value of i is (click to find out) I has the value 7 since to stay in the loop 'i' had to be smaller than 7. When i equals 7, the condition is met to exit the loop.

Q: Another question. Can you use i later on in the program?

Can I use the variable i later? (click to find out) Yes you can. It is a standard variable just like any other. It is best not to do this too often as you will want to keep the variable 'i' just for looping. This is just a convenience for you to remember that the variable 'i'' may be used for other loops throughout the code.

How to setup a count down for loop

You can create a for loop that counts down by changing all three parameters in the for loop. Lets say you want to count down from 10 to 1 (ten iterations round the loop).

void setup (void) {


   Serial.println("Arduino count down for loop");
   for (int i=10; i>=1; i--) {
      Serial.print("i is : ");

void loop(void) {
Here's the count down output:
Arduino count down for loop
i is : 10
i is : 9
i is : 8
i is : 7
i is : 6
i is : 5
i is : 4
i is : 3
i is : 2
i is : 1

Test Yourself

Q: Here's the same question for you. What is the value of i after the loop has finished executing?

The value of i is (click to find out) I has the value 0 since 'i' had to be greater than or equal to 1 to stay in the loop.

Arduino For loop Array Example

The reason that you start with the control loop variable at zero is that arrays are defined starting from index zero. If you don't use zero as an initial starting point then you can get an off by one error - meaning you can write to a array location that does not exist. For an array of 10 values only indices 0..9 are valid.

Note: Note: Even if the array position does not exist, the loop will still write data to that location - meaning you are overwriting other variables - an extremely bad idea!

Here's an example of setting up an array initialising each element with a random number. Then printing out the array values in turn.

int myarray[10];

void setup (void) {


   for (int i=0; i<10; i++) myarray[i]= random(100);

   Serial.println("Arduino for loop");
   for (int i=0; i<10; i++) {
      Serial.print("i is : ");
      Serial.print(" array value is ");

void loop(void) {
The random number output is not truly random unless you supply a seed value - that should also be from a random source - such as a button press capturing the millis() timer value - a truly random seed.

This is because the random data is created from an algorithm and if it starts from the same seed number all the values will repeat. If you run the program again you will see the same set of numbers. For this code it does not matter.

The randomness of the function is in the unpredictability of the number sequence.

Standard form of a for loop

The standard form of the for loop initialises the control variable to 0. For exiting the loop the condition tests whether the variable is smaller than the number of loops needed. You don't have to use this but it makes life easier when dealing with arrays.

The value of 'i' goes from 0 to 9 for the code within the curly braces. So it traverses 10 values. The reason it is easier for array use is that arrays start from index zero.

TIP: it is best to use the standard form of the Arduino for-loop so that you never access an array value incorrectly.

The standard form is this:

   for (int i=0; i<10; i++) {
      <block of code to execute>

At the end of the loop code (outside curly braces) the value of 'i' will be 10, because when 'i' reaches 10 the statement 'i<10' is false so the loop is exited.

Note: At the end of the loop 'i' has the value 10.

Initialising the For Loop

In the examples above the for-loop initialisation code is used as follows:
int i=0;
The variable is both declared and initialised - this is a C++ feature.

In C code you can't declare the variable within the for loop stricture. It must be declared outside the for loop.

This is because C compliers want all the RAM assigned before messing around creating the fixed program code. In C++ an extra stage of processing allows the RAM and program data to be assigned on the fly. So for pure 'C' code you will find:
void myFunction(void) {
int i;

   for(i=0;i<10;i++) {

   for(i=10;i>0;i++) {

Note: You can use either form in C++ code i.e. when coding for Arduino.

You might want to follow the standard C form as you can't declare a variable twice in the same code block. So if you copy and paste some loop code into existing code, you would have to look back and remove the extra declarations. That or wait for the compiler to complain, which it will!


How many times the loop function runs

One question is:

    "How many times loop function runs in Arduino IDE:"

The loop function in Arduino code is what is known as an infinite loop which is can either be written using a while structure or a for loop structure:

Infinite While loop

The while loop is used slightly differently to the for loop and does not have an iterator.

   while(1) {
// Do something forever

Infinite For loop

The format of the infinite for loop is slightly strange:
   for(;;) {
// Do something forever
The code operates exactly the same as the while loop. The two semicolons just mean that the initialiser, the conditional test and the iterator are void i.e. they do not exist. The compiler just leaves these parts out, and all that is left is the assembler jump back instruction. So the loop continues forever.

Either of these looping structures could be used in the Arduino code. The are known as infinite loops but this really is just qualified by the lifetime of the program. This is from the start time, when you either apply power or press reset. It obviously end when power is removed or rest is pressed again.

So to answer the question

    "How many times loop function runs in Arduino IDE"

The answer is - "it depends!"

It depends on the crystal speed of the Arduino (16MHz). This defines how many instructions per seconds can be executed.  And it depends on how long the power is applied. The last factor is how much code is executed within the main loop().

So it depends on:

  1. Processor clock speed,
  2. How long power is applied,
  3. How much code is within loop().

When you add more instructions inside loop(), mode code must be executed so the loop time increases. 

Measuring Loop Time

You can measure the loop time e.g. using microseconds timer but collect the data in a variable and then compute the average. If you use a Serial.print statement within the measurement it will give a larger the time period - as that code itself will take a long time.

To do it add a condition that prints out the data after 100 loops. However, even the test itself will take time but it will be a small proportion of the time if the main code is substantial.

New! Comments

Have your say about what you just read! Leave me a comment in the box below.

Privacy Policy | Contact | About Me

Site Map | Terms of Use

Visit our Facebook Page:

   Click Here

Recent Articles

  1. The TP4056: Lithium Ion/polymer Battery Charger IC

    Learn how to use the TP4056 properly. There's a right way, and a wrong way, to use it to safely charge Lithium Ion batteries.

    Read more

  2. How to use the MCP4728, a versatile four channel DAC with built in voltage reference.

    The MCP4728 chip is a four channel 12 bit DAC, with memory that outputs voltage that you can use for calibration, anywhere you want a fixed voltage.

    Read more

  3. Secrets of the Hitachi HD44780 LCD: How to display text and bargraphs.

    Find out how to connect the Hitachi HD44780 and use it to display text and graphics in any of your projects.

    Read more

  4. INA219: A voltage and current sensing chip using I2C

    INA219: How to use the INA210 for maximum accuracy in current and power measurements

    Read more

  5. Arduino Oversampling: How to Get More ADC Bits with No Extra Hardware!

    Arduino oversampling is a technique to increase ADC resolution by reading more samples then decimating. It really does work!

    Read more

  6. How to use the ADS1115

    A tutorial on using the ADS1115 precision 16 bit ADC for low power use.

    Read more

Readers Comments

"I wanted to thank
you so so so much
for all the information
you have provided in
your site it's


- Ranish Pottath

"This site really is
the best and my favorite.
I find here many useful
projects and tips."

- Milan


"Awesome site,
very, very easy and nice
to navigate!"

- Matt

Learn Microcontrollers

"Interested in

Sign up for The
Free 7 day guide:


"I am a newbie to PIC
and I wanted to say
 how great your
site has been for me."

- Dave


"Your site is a great
and perfect work.

- Suresh


"I couldn't find the correct
words to define
yourweb site.

Very useful, uncovered,
honest and clear.

Thanks so much for
your time and works.

- Anon

Back to Top