Computers excel at performing repetitive tasks without getting bored. Loops are the primary way we tell them to do so.
Key Uses:
while
LoopThe 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.
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.
for
LoopThe "counting loop". Perfect for when you know how many times you want to iterate.
for (initialization; condition; increment) {
// Code to execute
}
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.
do-while
LoopThe "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.
Problem: Designing a concrete beam. The height h
must be a positive, non-zero value.
Logic:
A do-while
loop guarantees the prompt happens at least once, and repeats only if the input is bad.
for
loop
while
loop
do-while
loop
GOTO
to StructureEarly Languages (FORTRAN, BASIC):
IF
and GOTO
statements.10 PRINT X
20 X = X + 1
30 IF X < 100 GOTO 10
The Problem: "Spaghetti Code"
GOTO
s made logic incredibly hard to follow.The Solution: Structured Programming
for
, while
) with clear entry and exit points. This was a revolutionary step in software engineering.Sometimes Less is More.
History is finite, because time has a beginning(?).
Key Concepts:
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).Remember the Pitfalls:
<
vs <=
) to prevent off-by-one errors.