The for loop in C++ is a control structure used to repeat a block of code a specific number of times. It is particularly useful when the number of iterations is known beforehand. The for loop combines the initialization of a loop variable, a condition to test, and an update expression into a single line, making it a concise and efficient way to handle iteration.
for(initialization; condition; update) {
// code to be executed
}
• Initialization: This is where you set up your loop variable.
• Condition: The loop continues as long as this condition evaluates to true.
• Update: This expression updates the loop variable after each iteration.
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 5; ++i) {
cout << "Iteration: " << i <<
endl;
}
return 0;
}
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
A nested for loop is a for loop inside another for loop. The inner loop runs completely each time the outer loop runs once. This can be useful for working with multi-dimensional arrays or performing complex iterative operations.
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 4; ++j) {
cout << "(" << i
<< ", " << j << ") ";<< endl;
}
}
return 0;
}
(0, 0) (0, 1) (0, 2) (0, 3)
(1, 0) (1, 1) (1, 2) (1, 3)
(2, 0) (2, 1) (2, 2) (2, 3)
An infinite for loop runs indefinitely because the loop condition is always true. This can be useful in situations where you need a loop that continuously executes until an external condition is met.
#include <iostream>
using namespace std;
int main() {
for(;;) {
cout << "This loop will run forever." << endl;
}
return 0;
}