Why Do We Need Loops?

Computers excel at performing repetitive tasks without getting bored. Loops are the primary way we tell them to do so.

Key Uses:

  • Processing collections of data (arrays, lists, etc.)
  • Running simulations that evolve over time
  • Repeating a task until a specific condition is met
  • Implementing algorithms that require iteration

The while Loop

The most fundamental loop. It repeats a block of code as long as a condition is true.


          while (condition) {
              // Code to execute
              // ...
              // Something inside the loop should
              // eventually make the condition false!
          }
        

The condition is checked before each iteration. If it's false the first time, the loop body never runs.

Math Example: Approximating π

Problem: How Mādhava of Sangamagrāma calculated π?

The Series:

\[ \frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \dots \]

Logic: We don't know how many terms we need. We'll use a while loop to keep adding terms until the term we're adding is very small (i.e., it doesn't change the result much). This is an ideal use case for a while loop.

The for Loop

The "counting loop". Perfect for when you know how many times you want to iterate.


          for (initialization; condition; increment) {
              // Code to execute
          }
        
1. initialization: Runs once at the very beginning.
2. condition: Checked before each iteration.
3. increment: Runs at the end of each iteration.

EE Example: RMS Voltage

Problem: Calculate the Root Mean Square (RMS) voltage from N discrete samples. RMS value is the "effective" voltage of a varying signal.

Formula:

\[ V_{rms} = \sqrt{\frac{1}{N}\sum_{i=1}^{N} v_i^2} \]

Logic: We need to sum the squares of N voltage samples. A for loop is perfect because we have a fixed number of samples to process.

The do-while Loop

The "execute at least once" loop. The condition is checked after the loop body runs.


          do {
              // This code always runs at least once
          } while (condition); // Note the semicolon!
        

Key Use Case: Input validation. You need to get the input first, then check if it's valid.

Civil Eng: Input Validation

Problem: Designing a concrete beam. The height h must be a positive, non-zero value.

Logic:

  1. Prompt the user to enter the beam height.
  2. Read the value.
  3. Check if the value is valid.
  4. If it's not valid, go back to step 1.

A do-while loop guarantees the prompt happens at least once, and repeats only if the input is bad.

Choosing the Right Loop

for loop

  • Use when: You know the number of iterations in advance.
  • Keywords: "For each item...", "Do this N times", "Count from A to B".

Choosing the Right Loop

while loop

  • Use when: The number of iterations is unknown and depends on a condition. The loop might not run at all.
  • Keywords: "While this is true...", "Until this happens...".

Choosing the Right Loop

do-while loop

  • Use when: You need the loop body to execute at least once.
  • Keywords: "Get input and repeat if invalid", "Do this once, then check if we should do it again".

Historical Perspective: From GOTO to Structure

Early Languages (FORTRAN, BASIC):

  • Loops were constructed with IF and GOTO statements.
  • 10 PRINT X
  • 20 X = X + 1
  • 30 IF X < 100 GOTO 10

The Problem: "Spaghetti Code"

  • Unrestricted GOTOs made logic incredibly hard to follow.
  • Debugging was a nightmare.

The Solution: Structured Programming

  • Languages like ALGOL and C introduced structured loops (for, while) with clear entry and exit points. This was a revolutionary step in software engineering.

When your condition overflows

Genie Meme

Sometimes Less is More.

Finding nemo

Uparrow Meme

History is finite, because time has a beginning(?).

Summary

Key Concepts:

  • Loops automate repetitive tasks.
  • for: For counting a known number of iterations.
  • while: For repeating based on a condition (may not run).
  • do-while: For repeating based on a condition (runs at least once).

Summary

Remember the Pitfalls:

  • Avoid infinite loops by ensuring the condition can become false.
  • Double-check your loop bounds (< vs <=) to prevent off-by-one errors.
  • Watch out for stray semicolons that terminate your loop statement prematurely.