# How do I stop and exit out of a 'for loop'

Hello all,
I just got my first Arduino board. I am going to use it to interface with my wife’s car lock system.

Heres the code I’ve got so far.

for (analog2 = HIGH; counter <= 5000; counter + 5)
{
analog3 = HIGH; // fire siren
if (analog1 = HIGH); // look for disarm signal
analog3 = LOW;
analog4 = LOW;

}
}
Problem is I need a way to terminate the loop early if an external signal is recieved. Can anyone help me.
Thankyou.

``````for (int i = 0; i < 1000; i++)
{
if (i == 137)
break;
};
``````

The loop will end when the value of i reaches 137.

Assuming you can input the ‘presence’ of external signal into the program somehow:

You can either use a while loop instead of for loop.

``````while ( external_signal != 1 && counter <=5000 ) {    //if no external signal is received then keep looping
counter+=5;
//rest same
}
``````

OR you can even put a condition within your existing for loop, for example:

`````` for (analog2 = HIGH; counter <= 5000; counter + 5)
{
if ( external_signal == 1 ) {
counter = 5001;                   //if an external signal is received, force the counter to 5001 already
}
//rest same
}
``````

"counter = 5001" is silly. If you want to break out of the loop, use break. You should say what you mean, not any random thing that happens to work. :)

hobbified: "counter = 5001" is silly. If you want to break out of the loop, use break. You should say what you mean, not any random thing that happens to work. :)

To clarify, think about what would happen if you need to use the value of the counter at some point later in the sketch to perform some action. That's why you want to use break; e.g. a simple linear search on an array where you want to know the index of the element you found.

Thankyou all, many good ideas, this will help.