for Loop
Basic Syntax
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;
// Output: 0 1 2 3 4
return 0;
}Counting Down and Custom Steps
// Count down from 10 to 1
for (int i = 10; i >= 1; i--) {
cout << i << " ";
}
cout << endl;
// Step by 2
for (int i = 0; i <= 20; i += 2) {
cout << i << " ";
}
cout << endl;Multiple Variables with the Comma Operator
The init and increment sections can each hold more than one expression, separated by commas. This is handy when two counters need to move together, such as scanning a range from both ends inward.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = 8;
// i moves forward, j moves backward, in the same loop
for (int i = 0, j = n - 1; i < j; i++, j--) {
cout << "swap positions " << i << " and " << j << endl;
}
return 0;
}Infinite for Loops
for (;;). It runs forever unless something inside the body (typically a break or a return) ends it. This pattern is common for event loops or servers that run "until told to stop."#include <iostream>
using namespace std;
int main() {
int count = 0;
for (;;) {
cout << "Iteration " << count << endl;
count++;
if (count >= 3) {
break; // the only way this loop ends
}
}
return 0;
}Nested for Loops
A for loop can contain another for loop. The inner loop completes all of its iterations for every single iteration of the outer loop. Nested loops are the standard way to work with two-dimensional data, like a grid or matrix.
#include <iostream>
using namespace std;
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
cout << row * col << "\t";
}
cout << endl;
}
return 0;
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9for vs while
Key Points
A for loop has three parts: initialization, condition, and increment/update.
All three parts are optional; for (;;) creates an infinite loop that needs an internal break to stop.
The comma operator lets you initialize/update multiple variables in one loop header.
Nested for loops iterate the inner loop fully for every outer iteration - useful for grids and matrices.
Prefer for when the number of iterations is known in advance; prefer while for open-ended conditions.