Stop an unbounded iteration
while (true) { double prod = a*x; if (fabs(1.0 - prod) < eps) { break; } x *= (2.0 - prod); } The loop deliberately has no terminating condition. Each iteration computes prod, tests whether the approximation is close enough, and uses break to leave the loop immediately when it is. section 3.2
A break statement immediately terminates the nearest enclosing loop or switch statement. In a loop, it skips the rest of the dependent block and does not reevaluate the termination condition; control resumes with the statement after the loop. The usual syntax is simply break;. section 3.2 section 3.3
TAKEAWAY
- Use break when the stopping decision belongs inside the loop body, separating computation, stopping logic, and state updates. section 3.2
- In a switch statement, break transfers control to the statement after the switch and prevents execution from falling through into later cases. section 3.3
- Do not confuse break with continue: continue skips the remaining statements in the current iteration, then reevaluates the loop condition. section 3.2
while (true) {
double prod = a*x;
if (fabs(1.0 - prod) < eps) { // Stops if close enough
break;
}
x *= (2.0 - prod); // Heron approximation
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":5}],[{\"line\":0,\"ch\":7},{\"line\":0,\"ch\":11}],[{\"line\":1,\"ch\":2},{\"line\":1,\"ch\":8}],[{\"line\":2,\"ch\":2},{\"line\":2,\"ch\":4}],[{\"line\":2,\"ch\":6},{\"line\":2,\"ch\":10}],[{\"line\":3,\"ch\":4},{\"line\":3,\"ch\":9}]]"}
!@%STYLE%@!
Inspect the complete while-loop pattern, including the internal tolerance test, break statement, and update that follows only when continuation is needed. section 3.2






