Doing It Again
A loop repeats a block of code. The staple forms are the while loop and the for loop.
A while loop runs as long as a condition stays true, checking it before each pass. Correct execution requires three ingredients:
| Ingredient | Role in Code | Example |
|---|---|---|
| Initialization | Sets start point | i = 0 |
| Condition | Decides when to stop | i < 5 |
| Update | Moves toward false | i = i + 1 |
Forget the update, and you get an infinite loop that freezes the program by running forever.
A for loop handles known repetitions or steps through collections. For example, produces values starting at 0 and stopping before :
Control and Pitfalls
The for loop convention stops before , a frequent source of the off-by-one error where a loop runs one time too many or too few because a boundary like < versus <= is wrong.
Two control statements adjust loops internally:
| Statement | What It Does |
|---|---|
break | Exits the loop immediately |
continue | Skips to the next iteration |
Loops can also nest, placing one inside another. If an outer loop runs times and an inner loop runs times, the inner body executes times, directly impacting performance.