Team 2550
Technical Documentation
 All Files Variables Pages
Loops

Table of Contents

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.

while

A while loop allows you to repeat code until a condition is met. The basic layout follows...

while (condition_is_true)
{
    ...
    ...
    ...
}
Note
Any kind of loop can be nested.

There are many uses for while loops. Here are a few examples.

#include <iostream>
using namespace std;
int main() {
int i = 0;
//this code in this loop runs exactly 100 times
while (i < 100)
{
cout << 2*i << endl;
i++; //update i, the loop would be infinte otherwise
}
int i = 1;
//repeat until i = 0
//This loop will continuously add to i while i is not 0. Once i reaches around 4 billion,
// it will actually wrap around and become approximately -4 billion (4 billion is the
// approximate size of a signed int on a 32 bit system). After wrapping, it will approach
// 0 and eventually reach it.
while (i != 0)
i++; //like an if statement, a single-line while loop does not need brackets
//Here is a loop that relies on an external factor. It keeps repeating until the user provides valid input.
int answer;
cout << "Guess what number I am thinking of: ";
cin >> answer;
while (answer != 42)
{
cout << "You answered incorrectly, please try again.\n"
cin >> answer;
}
}

While loops can be especially useful for robotics. Here are a few more usage ideas.

  • Move until a sensor's readings yield a certain value.
  • If the robot is remote-controlled, the code that translates user inputs into actions is all in a loop.
  • A combination of loops and functions can be used to multi-task. You can only run a single action at a time, but the program executes as fast as possible, meaning that you can work on one task, switch out of it, and move to another until they are all done.

do-while

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);
Warning
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.

int answer;
cout << "Guess what number I am thinking of: ";
do
{
cin >> answer;
"You chose poorly. Try again.\n";
} while (answer != 42);

for

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.

for (int i = 0; i < 100; i++)
cout << 2 * i << endl;

The breakdown of this code is very simple:

  1. Declare an int called i and initialize it
  2. The test to run
  3. Increment i (this can be any mathematical operation)
Note
For loops have one more benefit: i is localized. In other words, i only exists only within that loop (and is deleted afterwords). In general, reusing variables is a bad idea.
Any section in the for loop can be omitted, however, note that for (;;) creates an infinite loop.

Pitfalls

There are several situations that should be avoided whenever you are working with loops.

//This nested loop reuses i. Because i is reset in the second loop, this is an infinite loop.
for (int i = 0; i < 100; i++)
{
cout << i << endl;
for (i = 0; i < 10; i++)
cout << i << endl;
cout << endl;
}
//It is legal to redeclare i, but it is not a good idea here. You cannot access the original i.
for (int i = 0; i < 100; i++)
{
cout << i << endl;
for (int i = 0; i < 10; i++) //note the int in front of this (more local) i.
cout << i << endl;
cout << endl;
}
//This loop will work perfectly. Whenever there are multiple instances of i, the most local is always chosen.
//The problem is that the code can be confusing, and it is very easy to forget `int i = 0` is not the same as `i = 0`

Floating Point Operations in 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)

//This loop may be infinite on some systems. While we know `.1 * 10 = 1`, the computer does not.
//Because certain decimal values are not possible to express exactly in binary, it is likely that the exact value of 1 will be missed (the result may actually be something like `1.0000000000001`).
for (float i = 0; i != 1; i += .1)
cout << i << endl;
//In order to get the desirable result, remove the equality comparison operator.
for (float i = 0; i < 1; i += .1)
cout << i << endl;
//If you are working with a sensor (or anything else that results in a decimal value), always make the condition a range instead of an exact value).
//We are assuming that the function `read()` is defined and returns a floating point value.
float result = read();
while (result < 3.14 && result > 3.15) //this will work
{
cout << "looping\n";
result = read();
}
float result = read();
while (result != 3.1415) //this will probably fail and be infinite
{
cout << "looping\n";
result = read();
}
Warning
The general rule with anything floating-point related: do not use == or != when working with floating point values. Doing so will often yield undesirable results. Use a range like the above example.
Remember that the ! operator can be placed at the beginning of a parenthesized expression and negate the answer !(expression).