🔁

Programming Logic and Design: For Loop

May 23, 2024

Programming Logic and Design: For Loop

Introduction

  • For Loop: A definite loop that executes a specific number of times.
  • Example: The loop will execute exactly 4 times (0, 1, 2, 3).

Key Actions in For Loop

  1. Initialization: Setting the count to zero.
  2. Evaluation: Checking if the count is less than or equal to 3.
  3. Alteration: Incrementing count by 1.

Steps in Execution

  • Initial value count = 0.
  • Evaluate if 0 <= 3 (true) → Output "hello" → Increment to count = 1.
  • Evaluate if 1 <= 3 (true) → Output "hello" → Increment to count = 2.
  • Evaluate if 2 <= 3 (true) → Output "hello" → Increment to count = 3.
  • Evaluate if 3 <= 3 (true) → Output "hello" → Increment to count = 4.
  • Evaluate if 4 <= 3 (false) → Exit loop.

Comparison: For Loop vs. While Loop

  • For Loop: Fewer lines of code (3 lines).
  • While Loop: More lines of code (5 lines).
    • Initialization before entering the loop.
    • Evaluation condition.
    • Output statement.
    • Increment count.
    • Re-evaluate condition and repeat steps.

Efficiency

  • For Loop: Loop control variable is handled automatically, leading to fewer lines of code and increased processing time.

Step Value

  • Default: Step value is 1.
  • Can be positive or negative.
  • Programmers can specify any step value.
  • Example: Increment by 2 → 2, 4, 6, etc.

Structure of For Loop

  • Keywords: for and endfor.
  • Variables:
    • Loop control variable (e.g., count).
    • Initial value.
    • Final value (end of iteration).
    • Step value (amount changed per loop).

Types of Loops

  • Pre-test Loop: Control variable tested before each iteration (for loops and while loops).
  • Post-test Loop: Control variable tested after each iteration (do-while and do-until loops).

Next Topic

  • Will discuss common loop applications in the next video.