Loops: for, while and do-while
Repeat work with for, while and do-while loops, plus break and continue.
What is Loops: for, while and do-while?
Loops run the same block several times. for suits a known number of steps, while repeats until a condition fails, and do-while always runs its body at least once.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
See how it works
Press Step to run the loop one move at a time. Watch the condition being checked, the body running and the trace table growing row by row.
C and C++ code examples
#include <stdio.h>
int main(void) {
/* for: start; condition; step */
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
/* while: repeat as long as the condition holds */
int n = 20;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
printf("halved %d times\n", steps);
/* do-while: the body runs at least once */
int tries = 0;
do {
tries++;
} while (tries < 3);
printf("tries = %d\n", tries);
/* break leaves the loop, continue skips to the next round */
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
if (i > 7) break;
printf("%d ", i);
}
printf("\n");
return 0;
}
1 2 3 4 5
halved 4 times
tries = 3
1 3 5 7
#include <iostream>
#include <vector>
int main() {
// for: start; condition; step
for (int i = 1; i <= 5; i++) {
std::cout << i << ' ';
}
std::cout << '\n';
// while: repeat as long as the condition holds
int n = 20;
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
std::cout << "halved " << steps << " times\n";
// do-while: the body runs at least once
int tries = 0;
do {
tries++;
} while (tries < 3);
std::cout << "tries = " << tries << '\n';
// range-based for visits every element of a container
std::vector<int> values{1, 3, 5, 7};
int sum = 0;
for (int value : values) {
sum += value;
}
std::cout << "sum = " << sum << '\n';
}
1 2 3 4 5
halved 4 times
tries = 3
sum = 16
C and C++ comparison
The for header holds the start, the condition and the step. break leaves a loop early and continue jumps to the next round. C++ adds the range-based for, which visits every element of a container without an index.
C exposes small procedural APIs and makes representation details explicit.
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Loops in C and C++
for (int i = 0; i < n; i++) { ... } | Repeat n times |
while (condition) { ... } | Repeat while the condition is true (may run zero times) |
do { ... } while (condition); | Runs the body at least once |
for (int x : values) | C++11 range-based for over a container |
for (const auto& item : items) | C++: range-for without copying each element |
break; continue; | Leave the loop, or skip to the next iteration |
for (int i = n - 1; i >= 0; i--) | Count down |
for (;;) { ... } | Infinite loop, ended with break |
Common mistakes with loops
Off by one with <=
Array indexes run from 0 to n - 1, so i <= n reads one element past the end.
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i <= 5; i++) printf("%d ", a[i]); /* reads a[5] */
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) printf("%d ", a[i]);
A semicolon after the for header
for (...); has an empty body, so the block below runs only once.
for (int i = 0; i < 3; i++);
{
printf("hi\n"); /* printed once */
}
for (int i = 0; i < 3; i++) {
printf("hi\n");
}
Counting down with an unsigned index
An unsigned value is never negative, so i >= 0 is always true and the loop never ends.
for (size_t i = n - 1; i >= 0; i--) { /* never stops */ }
for (size_t i = n; i-- > 0; ) { /* visits n-1 down to 0 */ }
Frequently asked questions
What is the difference between while and do-while?
while checks the condition first, so the body may never run. do-while runs the body once before checking, which suits menus and input validation.
When should I use a for loop instead of while?
Use for when you know how many times to repeat or are counting through a range. Use while when the loop depends on a condition that changes inside it, such as reading input until the end.
How do I loop through a vector in C++?
Use a range-based for: for (const auto& value : values). Use an index loop (for (size_t i = 0; i < values.size(); ++i)) when you need the position.
How do I exit a nested loop?
break only leaves the innermost loop. Use a flag checked by the outer loop, move the loops into a function and return, or (in C) use goto to a label after the loops.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Sum of Odd Numbers Add every odd number up to a limit. Easy
- Countdown to Liftoff Count down from a number and end with Liftoff! Easy
- Multiplication Table Row List the first multiples of a number. Easy