In C++, a for loop is used to repeat a block of code a certain number of times. It consists of three main parts:
1. Initialization: This part is executed once at the start of the loop. It usually initializes a counter variable.
2. Condition: This is evaluated before each iteration. If it evaluates to true, the loop continues; if false, the loop terminates.
3. Increment/Decrement: This part is executed after each iteration. It typically updates the counter variable.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
Example:
#include <iostream>
using namespace std;
int main() {
// for loop starts with initialization of i = 1, continues while i <= 5, and increments i by 1 each time
for (int i = 1; i <= 5; i++) {
cout << i << endl; // prints the value of i in each iteration
}
return 0;
}
Output:
1
2
3
4
5
2
3
4
5
Explanation:
- Initialization: int i = 1 initializes the loop variable i to 1 before the loop starts.
- Condition: i <= 5 checks whether i is less than or equal 5. If this condition is true, the loop executes; if false, the loop exits.
- Increment: i++ increases the value of i by 1 after each iteration.
Example: Print the table of 2 through for loop
#include <iostream>
using namespace std;
int main() {
for (int i = 2; i <=20; i=i+2)
{
cout << i << endl;
}
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
20
4
6
8
10
12
14
16
18
20