C++ Tutorial
C++ For Loop
for packs init, condition, and step in one line. Use it when you know how many times to repeat.
Three parts in one line
A classic for loop has three slots separated by semicolons: initialize, condition, step. The initialize runs once. Then C++ checks the condition, runs the body, runs the step, and checks again, until the condition is false.
That is the same three jobs a while loop has, written where you can see them together. Usefor when the number of passes is known: 0 to n minus one, 1 to 10, every index in an array.
A complete for program
int i = 0 starts the counter. i < 5 is the test. i = i + 1 is the step. The body prints the current i. The values printed are 0, 1, 2, 3, 4 — five times, not six.
Example
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i = i + 1) {
cout << i << endl;
}
return 0;
}Run this in /cpp/try. Counting from 0 is the usual C++ habit because array indexes start at 0.
Read the header left to right
| Slot | This example | When it runs |
|---|---|---|
| Init | int i = 0 | Once, before the first check |
| Condition | i < 5 | Before every pass, including the first |
| Step | i = i + 1 | After each pass, before the next check |
i++ means the same as i = i + 1 here. You will see ++ in other people's code. Either form is fine for a counter.
The variable declared in init exists only inside the loop. After the closing brace, i is gone.
Count the other way
Start high and subtract if you need a countdown. The condition still has to become false. Herei goes 5, 4, 3, 2, 1, then i >= 1 fails.
Example
#include <iostream>
using namespace std;
int main() {
for (int i = 5; i >= 1; i = i - 1) {
cout << i << endl;
}
cout << "done" << endl;
return 0;
}Range-for over a list
When you already have a collection and you want each value, C++17 gives you a range-based for:for (int n : nums). No index. No length. The loop binds n to each element in turn.
This works on a built-in array and on a vector. Include <vector> for the second. Arrays come in a later chapter; this is enough to walk a short list.
Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
int arr[] = {2, 4, 6};
for (int n : arr) {
cout << n << " ";
}
cout << endl;
vector<int> nums = {10, 20, 30};
for (int n : nums) {
cout << n << " ";
}
cout << endl;
return 0;
}Which loop to write
- Known count or indexes: classic
for. - Every element in an array or vector, no index needed: range-for.
- Keep going until a condition changes (input, a flag):
while.
A range-for does not give you the index. If you need the position as well as the value, use a classicfor with i.
Off-by-one
i < n runs n times when i starts at 0. i <= n runs n + 1 times. Both are valid; they mean different things. For an array of length n, the last valid index is n minus one, so the test is i < n.
Next: break and continue — leaving a loop early, or skipping one pass.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.
Physics
A drop, second by second
Ticker-tape and strobe photos show position at equal time steps. From rest, s = ½ g t². At t = 1, 2, 3, 4 s the distances are about 4.9, 19.6, 44.1, 78.5 m. The gaps grow because the object is speeding up.
s(t) = ½ g t²
Example
#include <iostream>
using namespace std;
int main() {
const double g = 9.81;
for (int t = 1; t <= 4; t++) {
double s = 0.5 * g * t * t;
cout << "t = " << t << " s, s = " << s << " m" << endl;
}
return 0;
}Maths
Sum of squares
1² + 2² + … + 10² is 385. The closed form n(n+1)(2n+1)/6 gives the same 385 for n = 10. The loop is how you check the formula before you trust it on n = 1000.
Σ k² = n(n+1)(2n+1)/6
Example
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int n = 1; n <= 10; n++) {
sum += n * n;
}
cout << "sum of squares = " << sum << endl;
return 0;
}