Team 2550
Technical Documentation
|
|
Iteration, or looping, refers to the repetition of a group of commands. Looping allows blocks of code to be repeated indefinitely. This is especially useful for robotics - the code that runs is almost always some form of loop.
A while
loop allows you to repeat code until a condition is met. The basic layout follows...
while (condition_is_true) { ... ... ... }
There are many uses for while
loops. Here are a few examples.
While loops can be especially useful for robotics. Here are a few more usage ideas.
There are some situations where you want to ensure the code within the loop runs at least once. This is where a do... while
loop is useful. Instead of running the test at the beginning of the loop, a do... while
loop tests at the end. The basic format is very similar to that of a while
loop.
do { ... ... ... } while (condition_is_met);
while (true)
creates in infinite loop, which is undesireable in most cases.The final example in the above section can be made more concise here.
In most cases, you want to loop for a known number of times. This can be done with while loops (as was shown above), but for
loops are much more concise and allow code to be more localized.
The breakdown of this code is very simple:
for (;;)
creates an infinite loop.There are several situations that should be avoided whenever you are working with loops.
Floating point numbers in loops, while sometimes necessary, can cause problems. Many people are not aware of this, but the float
and double
datatypes always have a certain amount of inaccuracy. The reason has to do with the nature of decimal and binary numbers themselves, and cannot be remedied. (COMPUTERPHILE VIDEO)
==
or !=
when working with floating point values. Doing so will often yield undesirable results. Use a range like the above example.!
operator can be placed at the beginning of a parenthesized expression and negate the answer !(expression)
.