For Loop in C++
A for loop in C++ is used to execute a block of code repeatedly for a fixed number of times. It is an entry-controlled loop because the condition is checked before executing the loop body.
Syntax of For Loop
for(initialization; condition; increment/decrement) {
// code to be executed
}
How For Loop Works?
Algo of for loop
- First, the initialization is executed (e.g., int i = 1).
- Then, the condition is checked.
- If the condition is true, the loop body executes.
- After execution, the increment/decrement step is performed.
- The condition is checked again.
- This process continues until the condition becomes false.
- When the condition becomes false, the loop stops.
Example: Multiplication Table of a Number
#include <iostream>
using namespace std;
int main() {
int n = 5;
for(int i = 1; i <= 10; i++) {
cout << n << " x " << i << " = " << n*i << endl;
}
return 0;
}
Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50
Explanation:
- The number n is initialized to 5.
- The loop runs from i = 1 to 10.
- In each iteration, the multiplication n × i is calculated and printed.
- The value of i increases by 1 after each iteration.
- The loop stops when i becomes 11.
Summary:
- for loop is used when the number of iterations is known or controlled.
- It is an entry-controlled loop.
- All three parts (initialization, condition, update) are written in a single line.
- If the condition is false initially, the loop will not execute.