Sometimes it is necessary to stop the loop’s execution from the inside the loop. For example, let’s say you want to step through the positive integers looking for the number x, where x + 90 = x2. Your plan is to step through the integers 0 through 11 and pop out of the loop when you find the solution. Change the code:
#include <stdio.h> int main(int argc, const char * argv[]) { int i; for (i = 0; i < 12; i++) { printf("Checking i = %dn", i); if (i + 90 == i * i) { break; } } printf("The answer is %d.n", i); return 0; }
Build and run the program. You should see
Checking i = 0 Checking i = 1 Checking i = 2 Checking i = 3 Checking i = 4 Checking i = 5 Checking i = 6 Checking i = 7 Checking i = 8 Checking i = 9 Checking i = 10 The answer is 10.
Notice that when break is called execution skips directly to the end of the code block.