Do repetitive work with loops: an Ohm table with for, capacitor discharge with while, break and continue.
If you need to do the same operation a hundred times, you don't write a hundred lines; you write a loop. C++ has three basic loops: for, while and do-while. Which one you choose depends on whether you know in advance how many times it will repeat.
for: a known number of repetitions
for has three parts: the start, the condition and the step to perform after each iteration. Imagine connecting resistors from 1 to 5 ohms to a fixed 12 V source:
#include <iostream>
int main() {
for (int r = 1; r <= 5; ++r) {
double current = 12.0 / r;
std::cout << "R=" << r << " ohm -> I=" << current << " A\n";
}
// while: an unknown number of repetitions (capacitor discharge)
double v = 5.0;
int step = 0;
while (v > 1.0) {
v *= 0.5;
++step;
std::cout << "step " << step << ": " << v << " V\n";
}
// continue: skip even numbers, add up the odd ones
int sum = 0;
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) {
continue;
}
sum += i;
}
std::cout << "Sum of odd numbers: " << sum << '\n';
return 0;
}
R=1 ohm -> I=12 A
R=2 ohm -> I=6 A
R=3 ohm -> I=4 A
R=4 ohm -> I=3 A
R=5 ohm -> I=2.4 A
step 1: 2.5 V
step 2: 1.25 V
step 3: 0.625 V
Sum of odd numbers: 25
The parts of a for loop
- int r = 1: runs once before the loop starts.
- r <= 5: checked before every iteration. If it is false, the loop ends.
- ++r: runs at the end of every iteration.
The variable r lives only inside the loop. If you try to access it after the loop, you get a compile error. As a counter, ++r and r++ do the same job; by habit the prefix form is preferred.
while: until the condition ends
We wrote a simple model that assumes the capacitor voltage halves at every step. We don't know in advance how many steps it will take; we only say "until it drops below 1 V". This is a typical case for while. The condition is checked before entering the loop. If the first check is false, the body never runs.
do-while: at least once
do-while tests the condition at the end of the iteration, so the body runs at least once. It is handy when asking the user for a valid value:
int value = 0;
do {
std::cout << "Enter a number from 1-10: ";
std::cin >> value;
} while (value < 1 || value > 10);
In this example the question is asked again whenever the input is invalid. (Repairing std::cin against letter input is also needed; the clear and ignore from the earlier lesson come in handy here.)
break and continue
break: ends the loop immediately.continue: skips the remaining lines and moves on to the next iteration.
In the example above, continue skipped the even numbers: 1+3+5+7+9 = 25.
Nested loops
You can write a loop inside another loop. While the outer one goes around once, the inner one runs from start to finish. This is used for multiplication tables or scanning two-dimensional data. The total number of iterations is the product of the loops' iteration counts: a 100 x 100 nested loop makes 10,000 iterations.
Infinite loop: a loop whose condition never becomes false locks up the program. If you forget to change v in the while (v > 1.0) loop, it will run forever. In embedded systems a deliberate infinite loop (while (true)) is the main program itself; but there too some work is done on every iteration and the system does not get stuck.
Don't build a loop with a decimal counter (for (double x = 0; x != 1.0; x += 0.1)). Because of accumulated rounding error, x may never be exactly 1.0 and the loop never ends. Use an int for the counter and calculate the decimal value inside the loop.
Try it yourself
- Calculate the sum of the numbers from 1 to 100 with
for. (The answer should be 5050.) - Print the Ohm table for 24 V with resistances starting at 10 ohms and increasing in steps of 10.
- In the capacitor example, set the starting voltage to 10 V; find how many steps it takes to drop below 1 V.
- Using
break, find the first number, counting up from 1, whose square is greater than 200.
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.