for(value = 0 ; value <= 255; value+=5) // fade in (from min to max)
what does the "for" mean? i was wondering if someone can make it so easy to understand like how ladyada explained "if" and "else"
Moderators: adafruit_support_bill, adafruit
for (value=0; value<=255; value+=5) // fade in (from min to max)for (i=0; i<10; i=i+1)for (i=0; i<10; i++)niksun wrote:"For" is a type of "loop" construct. A loop is simply a concept that allows something in our code to happen over and over again under some condition. The "for" loop construct has some variable that is initialized to a value and either increments or decrements each time the loop is executed--to a target value.
The "for" statement has three parts. The first initializes a variable to some value. The second represents some condition that must be true for the loop to be executed; once the condition is false, we are out of the loop. The third represents a change to the variable after each loop.
Let's take your example:
- Code: Select all
for (value=0; value<=255; value+=5) // fade in (from min to max)
In this "for" loop, value is a variable (it can change). It is initialized to 0. So long as value is less than or equal to 255, then the loop will continue to execute. After each iteration of the loop, value increments by 5 (value +=5 means value = value + 5). So this loop will execute 52 times: if value starts at 0 and is incremented by 5 after each execution of the loop, then it will take 52 times before it reaches 255. On the 53rd time, it will reach 260 (which is not less than 255), so we will break out of the loop.
Does this make sense?
Here's a simpler example. Suppose I wanted to execute the same thing 10 times:
- Code: Select all
for (i=0; i<10; i=i+1)
Typically, we write it as follows:
- Code: Select all
for (i=0; i<10; i++)
This is because "i = i + 1" is the same thing as "i += 1" which is the same thing as "i++".
Return to Arduino Starter Pack
Users browsing this forum: No registered users and 1 guest