A for
loop is a control flow statement that repeatedly executes a block of code a certain number of times based on a condition. It is commonly used when the number of iterations is known beforehand. The basic structure of a for
loop is:
for(initialization; condition; update) {
// code to be executed
}
- Initialization: This is executed once before the loop starts. Typically, it sets up a counter variable.
- Condition: This is checked before each iteration. If it is true, the loop continues; if false, the loop terminates.
- Update: This executes after each iteration, usually incrementing or decrementing the counter.
Example:
for(int i = 1; i <= 5; i++) {
printf(“%d “, i);
}
Flowchart of a for
loop:
- Start
- Initialize (Set
i = 1
) - Condition check (Is
i <= 5
?)- If
yes
, proceed to the next step. Ifno
, exit the loop.
- If
- Execute code (
printf(i)
) - Update (Increment
i
by 1) - Go back to condition check.
The output will be: 1 2 3 4 5
.