C++ For Loop
A for loop in C++ is used to repeat a block of code a specific number of times. It is commonly used when the number of iterations is known before the loop starts.
The for loop consists of three main parts: initialization, condition, and increment/decrement. These parts control how the loop runs.
Syntax
for(initialization; condition; increment/decrement) {
// code to be executed
}
How the For Loop Works
- Initialization – A variable is initialized before the loop starts.
- Condition – The loop continues to run as long as the condition is true.
- Increment / Decrement – Updates the loop variable after each iteration.
Example Program
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 5; i++) {
cout << "Number: " << i << endl;
}
return 0;
}
Output
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
Example: Printing Even Numbers
#include <iostream>
using namespace std;
int main() {
for(int i = 2; i <= 10; i += 2) {
cout << i << " ";
}
return 0;
}
Important Notes
- The for loop is best used when the number of iterations is known.
- The initialization part runs only once at the beginning.
- The condition is checked before every loop iteration.
- The increment or decrement runs after each loop iteration.
Next Topic
Next, learn about C++ While Loop.