How is the “continue” statement used in the C programming language?
In C language, “continue” is a control flow statement used to end the current iteration and skip the remaining code in the loop, moving on to the next iteration.
The continue statement is typically used at the condition check inside a loop. When the condition is true, continue will skip the code after the continue statement in the current loop and move on to the next iteration. If the condition is false, the code inside the loop will continue to be executed.
Here is an example using “continue” which is used to calculate the average of all odd numbers in an integer array:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] % 2 == 0) {
continue; // 跳过偶数
}
sum += arr[i];
count++;
}
printf("奇数的平均值为: %.2f\n", (float) sum / count);
return 0;
}
The continue statement is used in the above example to skip over even numbers in the array. When an even number is encountered, the continue statement will bypass the lines of code sum += arr[i]; and count++; without executing them. The program will then continue to the next iteration of the loop until it reaches the end.
The output shows that the average of odd numbers is 5.00, this is because only 1, 3, 5, 7, and 9 are odd numbers, and their average is 5.