C language basics: break and continue

1. Jump out of the loop statement: break

        We have already learned several ways of writing loop programs: while, do while, for and other statements. We know that these loop statements have a characteristic, that is, every time they loop, they must check whether the conditional expression of the loop is not. If true, continue the loop, if not, stop the loop. But in many practical situations, we need the program to end the loop when the loop condition is still established. For this case, the C language provides a keyword called break specifically for this situation. For example, we define a length of 10. Array, and find the subscript of the number with the value of 7 in the array through a loop. When this number is found, the loop ends, so we need to write a program. In order to keep the array subscript out of bounds during the loop, we need to specify the loop condition as the following The index is less than 10, and the if statement is used in the loop body to determine whether the number 7 is found. The program is as follows:

int array[10] = {5,3,2,6,4,7,9,8,0,1};
int i;
for (i = 0; i < 10; i++)
{
    if (array[i] = 7)
    {
        printf("%d\n", i);
        break;
    }
}

        You can see that in this loop, in order to keep the array subscript out of bounds, we set the loop condition to be less than 10, and in the loop body, find the subscript with a value of 7 in the array through the if statement and display its value, of course Then jump out of the loop through the break statement, that is to say, when the program executes the break statement, the entire loop will end, and the content that should continue the loop will not be executed. In the above program, the loop is executed 6 times, the value of i is 5, and then the rest of the content is not executed, and it ends directly.

        Of course, the break statement can also be used in while and do while statements.

    

2. Go directly to the next cycle: continue

        Different from the break statement that jumps out of the loop, the function of continue is to end the current loop, so that the program will not execute the subsequent programs in this loop, but directly return to the beginning of the loop to execute the program. For example, we will modify the above and the program. Now, change to display only numbers greater than or equal to 5:

int array[10] = {5,3,2,6,4,7,9,8,0,1};
int i;
for (i = 0; i < 10; i++)
{
    if (array[i] < 5)
    {
        continue;
    }
    printf("%d\n", i);
}

        注意,在上面程序中我们并没将printf语句写到if分支里,而是直接写在了循环体中,所以每次循环时都应该显示这个i的值,但是在if中我们判断如果数组中变量的值小于5时则执行continue语句,于是结束本次循环,进入下一次循环,所以只有当大于等于5时都会执行printf语句,所以结果为:

0
3
5
6
7

 欢迎关注公众号:编程外星人

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691258&siteId=291194637