Hardware Reference
In-Depth Information
In this example, the function check_status runs until it returns true . When
that happens, the variable button becomes true , and the while loop will be bro-
ken. It might be within a few milliseconds, or the system might wait indei nitely.
for Loop
In cases in which you need a portion of code to loop an exact number of times,
the for loop is used. It is similar to while , only it is written differently. The for
loop keeps track of the number of times it has run.
for (expression1; expression2; expression3)
{
instructions;
instructions;
}
This might look complicated, but don't worry; it is simple. It requires three
expressions:
expression1 is the initializer; it will initialize a variable.
expression2 is the conditional expression; as long as this condition is
true , the loop keeps on executing.
expression3 is the modii er; when a loop is completed, this action is
performed.
For example:
for (int i = 0; i < 10; i++)
{
myfunc(i);
}
In this example, a variable is dei ned with the name i . The variable is set to
zero, and each time the function myfunc is run, i is increased by one. Finally,
when i reaches 10, the loop stops before running myfunc . This saves you from
writing out all the commands one by one like this:
myfunc(0);
myfunc(1);
myfunc(8);
myfunc(9);
NOTE The name i is often used for a temporary variable in for() loops. It is short-
hand for “index.”
 
Search WWH ::




Custom Search