Are these two ways using FOR loop the same?

Hello all

I am having a bit of a hard time understanding how the for loops are working. I have found different examples on how to do things, but I am not entirely sure, that I have understood it fully.

I have made two bits of code wich are suppossed to do the same thing. What do you think, will these two approaches result in the same thing:

Code bit 1:

int varvalincrement = 1;

   for (int i = (PWMval-varval); i <= PWMval ; i = i + varvalincrement){
      analogWrite(PWMpin, i);
      if (i >= PWMval) varvalincrement = varvalincrement * -1;
      delay(inctimer);
   }

Code bit 2:

int varvalincrement = 1;

  for (int i = (PWMval-varval); i < PWMval; i = i + varvalincrement) { 
    analogWrite(PWMpin, i);  
    delay(inctimer);                  
  }

  for (int i = PWMval; i >= (PWMval-varval); i = i - varvalincrement) { 
    analogWrite(PWMpin, i);  
    delay(inctimer);     
  }

Thanks in advance

/Jacob

The first way adds an extra if:test in the middle, which will slow performance some.
This
analogWrite(PWMpin, i);
only has a range of 0 to 255 for i, don't need int's for variable types.

Okay, so they do the same, but the first one is being slower.

I see about the ints and why I don't need them in this case with the analogWrite command.

I am a bit confused about how these functions will be executed and when they will stop getting executed...

I mean, have I used the comparison operators correctly? I want this to start at some point (PWMval-varval) and increment all the way up to the PWMval value. Then I need it to go in the other direction. But what if the increments defined in the varvalincrements parameter is 3 or some higher number that makes the "i" variable go past the PWMval? Will the function then terminate before it puts the value to the "i" variable or after the 3 has been added to the "i" variable?

Hope you can understand my question..

I guess in that case ints would good.
Some how you need to ensure that
i < PWMval
stays <= 255, and this
i >= (PWMval-varval);
stays in the range <=255 and >=0

I don’t know what happens if you analogWrite >255, perhaps the extra above 255 are just ignored.
Try it see! Can’t hurt anything.