Explain the execution of a for loop with a flowchart and example.

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:

  1. Start
  2. Initialize (Set i = 1)
  3. Condition check (Is i <= 5?)
    • If yes, proceed to the next step. If no, exit the loop.
  4. Execute code (printf(i))
  5. Update (Increment i by 1)
  6. Go back to condition check.

The output will be: 1 2 3 4 5.