Break
There are situations when we need to exit the loop without testing the condition at the top or bottom of the loop. The break statement causes the innermost enclosing loop or switch to me terminated immediately.
Let’s look at the following function, which finds the first number divisible by num, between min and max.
int find(int min, int max, int num) { int i; int result = -1; for (i = min; i <= max; i++) { if (i % num == 0) { result = i; break; } } return result; }
After we find the result, we break from the loop.
Continue
The continue statement is applicable to loops (not to switch) and can be used to skip statements following the continue statement in that iteration of the loop, executing the test part immediately (In For loop, the control passes to the increment step).
Let’s look at the following function, which calculates average of non-negative numbers in the passed array.
float positive_avg(int arr[], int len) { int i; int sum = 0; int num = 0; for (i = 0; i < len; i++) { if (arr[i] < 0) continue; sum += arr[i]; num++; } if (num > 0) return sum * 1.0f / num; return 0; }
If we encounter a negative number, we simply use continue to skip doing any calculation in that iteration and jump to the increment component (i++) of the for loop.