for (int i = 0... fandamental C question

Hi,

With regards to the following code below. Why isn't i reset to zero every time it goes round the loop? Or in C does it automatically bypass this after the first time it has passed? I would have thought that assigning this variable would/should be done outside of the loop.

Thank you in advance.

void loop ()
{
for (int i = 0; i < 20; i ++)
{
digitalWrite (ledPin, HIGH);
delay (delayPeriod);
digitalWrite (ledPin, LOW);
delay (delayPeriod);
}
}

How do you know its not?

If only there was a way to see the value of i during the cycles of the for loop in some sort of monitor that worked via the Arduino's serial port. Sadly, we will just need to rely on guessing. :wink:

Post the complete code, please.

Try this code, you'll see that i is set to 0 at the start of each loop - you'll count 20 blinks getting slower and slower and then after the 20th it will suddenly speed back up (when loop() restarts)

void loop ()
{
   for (int i = 0; i < 20; i ++)
   {
     digitalWrite (ledPin, HIGH);
     delay ((i+1)*delayPeriod);
     digitalWrite (ledPin, LOW);
     delay ((i+1)*delayPeriod);
   }
}
for (a; b; c) statement;

is a shortcut for writing:

{
  a;
  while (b) {
    statement;
    c;
  }
}

As you can see, 'a' executes only once before the while() loop and 'c' executes after the contents of the loop

Walltree:
With regards to the following code below. Why isn't i reset to zero every time it goes round the loop?

Because of the syntax of the for-loop. General syntax is:

for ( init; condition; increment )
{
   statement(s);
}

The 'init' part is executed before the loop starts looping round and round.
And the 'init' part is just executed once before the looping starts and not 'in between looping'.

Perhaps look up some C/C++ beginners tutorials!