CodeTheRobot

C++ Beginner · Lesson 07 of 22

Loops: for, while and do-while

Counting loops, range-based for, conditions, break and continue.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain loops: for, while and do-while in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

for repeats a counted block, while repeats as long as a condition holds, and do-while always runs at least once. Range-based for (for (const auto& x : items)) is the safest way to visit every element of a collection.

Every loop needs a way to end. Check the condition, the update and the boundaries. An off-by-one error, such as <= size, reads one element past the end.

Guided lesson

Work through these steps

  1. 1.

    Read the loops: for, while and do-while example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

for (int joint = 0; joint < 6; ++joint) {
// Counted loop: joint takes the values 0 to 5 (< 6 stops before 6).
  std::cout << "joint " << joint << '\n';
// Print each joint number.
}
// End of the for loop.
double torque{0.0};
// Start with no torque.
while (torque < 5.0) {
// Repeat while the torque is below the 5 N·m limit.
  torque += 1.25;
// Raise the torque a step each time so the loop makes progress.
}
// End of the while loop; it ends after four steps.
int attempts{0};
// Count connection attempts.
do {
// Start a do-while: the body runs before the condition is checked.
  ++attempts;
// Count this attempt.
} while (attempts < 3 && !connect());
// Repeat while attempts remain and connecting failed; it always tries at least once.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Loops: for, while and do-while. Expected result: sum 55 steps 4

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>

int main() {
  int sum{0};
  // TODO: for loop: add i * i to sum for i = 1 to 5
  double torque{0.0};
  int steps{0};
  // TODO: while torque < 5.0: add 1.25 to torque and count the step
  std::cout << "sum " << sum << "\nsteps " << steps << '\n';
  return 0;
}

Expected output

sum 55
steps 4
Stuck? Show the full solution (try it yourself first)
#include <iostream>

int main() {
  int sum{0};
  for (int i = 1; i <= 5; ++i) sum += i * i;
  double torque{0.0};
  int steps{0};
  while (torque < 5.0) {
    torque += 1.25;
    ++steps;
  }
  std::cout << "sum " << sum << "\nsteps " << steps << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Print a table of 10 joint angles using for. Then write a while loop that ramps a velocity from 0 to a target in fixed steps, and a do-while that retries a simulated connection up to three times.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.