The for loop is a control structure that is used to execute a block of code a specific number of times. It is typically used when the number of iterations is known beforehand, making it an ideal choice for counting or iterating through arrays or collections.
for Loopfor (initialization; condition; update) {
// Code to execute repeatedly
}
true, the loop continues; if false, the loop ends.true, the loop body executes.false, the loop exits.false.for Loop#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Iteration: " << i << endl;
}
return 0;
}
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
for Loop with ArraysThe for loop is commonly used to iterate over arrays:
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << "Element at index " << i << ": " << numbers[i] << endl;
}
return 0;
}
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
for LoopA for loop can run indefinitely if the condition is always true. This can be intentional in cases where a break statement is used to exit the loop dynamically:
#include <iostream>
using namespace std;
int main() {
for (;;) {
cout << "This is an infinite loop!" << endl;
break; // Prevents actual infinite execution
}
return 0;
}
for LoopsYou can nest for loops to handle multi-dimensional data or complex scenarios:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << "(" << i << ", " << j << ") ";
}
cout << endl;
}
return 0;
}
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
break Statement: Exits the loop prematurely.
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
cout << i << " ";
}
// Output: 1 2
continue Statement: Skips the current iteration.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
cout << i << " ";
}
// Output: 1 2 4 5
n Numbers#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter a positive number: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "Sum of first " << n << " numbers is: " << sum << endl;
return 0;
}
5
Sum of first 5 numbers is: 15
for Loop VariationsMultiple Variables in Initialization:
for (int i = 0, j = 5; i < 5; i++, j--) {
cout << i << " + " << j << endl;
}
Skipping Initialization or Update:
int i = 0;
for (; i < 5;) {
cout << i << endl;
i++;
}
Reverse Looping:
for (int i = 5; i > 0; i--) {
cout << i << " ";
}
// Output: 5 4 3 2 1