The for Loop

Part of: Iteration

A Loop Built for Counting When you know exactly how many times to repeat, the for loop is the cleanest choice. It packs all three loop parts onto a single header line. The header has three sections separated by semicolons: - Initialization : int i = 1 (runs once) - Condition : i <= 5 (tested before each pass) - Update : i++ (runs after each body) Order of Execution The parts execute in a precise order: 1. Initialization runs once . 2. The condition is checked. If false, the loop ends. 3. The body runs. 4. The update runs. 5. Go back to step 2. So the sequence is init, (condition, body, update), (condition, body, update), ... until the condition is false. for and while Are Equivalent Every for loop can be rewritten as a while loop and vice versa. These two loops do the same thing: Use a for loop when the count is known; use a while loop when it depends on a condition you cannot predict. One practical difference remains: a counter declared in the for-header (i) disappears once the loop ends, while the while version's j, declared before the loop, stays in scope afterward. Variable Scope A loop variable declared in the for header has scope limited to the loop. After the loop ends, that

Challenge: Sum to N