c语言中continue语句

c语言中continue语句;执行continue语句后,循环体的剩余部分就会被跳过。

例子;

1、原始程序。输出矩形。

#include <stdio.h>

int main(void)
{
    int i, j, height, width;
    puts("please input the height and width.");
    do
    {
        printf("height = "); scanf("%d", &height);
        if (height <= 0)
            puts("the range of height is > 0 ");
        printf("width = "); scanf("%d", &width);
        if (width <= 0)
            puts("the range of width is > 0 "); 
    }
    while (height <= 0 || width <= 0);
    
    for (i = 1; i <= height; i++)
    {
        for (j = 1; j <= width; j++)
        {
            putchar('*');
        }
        putchar('\n');
    }
    return 0;
}

当height和width都大于0时,程序正常输出矩形。 

当height <= 0时,此时程序已经满足do语句重新执行的条件,但是任然执行width的输入,因此需要改进。以下使用break改进。

2、使用break

#include <stdio.h>

int main(void)
{
    int i, j, height, width;
    puts("please input the height and width.");
    do
    {
        printf("height = "); scanf("%d", &height);
        if (height <= 0)
        {
            puts("the range of height is > 0 ");
            break;
        }
        printf("width = "); scanf("%d", &width);
        if (width <= 0)
            puts("the range of width is > 0 ");
    }
    while (height <= 0 || width <= 0);
    
    for (i = 1; i <= height; i++)
    {
        for (j = 1; j <= width; j++)
        {
            putchar('*');
        }
        putchar('\n');
    }
    return 0;
}

当height和width都大于0时程序正常执行,但是当height小于等于0时,程序就直接退出了。 以下使用continue语句改进。

3、使用continue

#include <stdio.h>

int main(void)
{
    int i, j, height, width;
    puts("please input the height and width.");
    do
    {
        printf("height = "); scanf("%d", &height);
        if (height <= 0)
        {
            puts("the range of height is > 0 ");
            continue;
        }
        printf("width = "); scanf("%d", &width);
        if (width <= 0)
            puts("the range of width is > 0");
    }
    while (height <= 0 || width <= 0);
    
    for (i = 1; i <= height; i++)
    {
        for (j = 1; j <= width; j++)
        {
            putchar('*');
        }
        putchar('\n');
    }
    return 0;
    
}

当height小于等于0时,程序会跳过循环体的剩余部分。

执行continue语句后,循环体的剩余部分就会被跳过。

例子:

#include <stdio.h>

int main(void)
{
    int i, j;
    puts("please input an integer.");
    printf("j = "); scanf("%d", &j);
    
    for (i = 1; i <= j; i++)
    {
        if (i == 6)
            break;
        printf("%d ", i);
    } 
    putchar('\n');
    puts("xxxxxyyyyyy");
    
    return 0;
}

 break语句会直接终止循环。

下面看continue。

#include <stdio.h>

int main(void)
{
    int i, j;
    puts("please input an integer.");
    printf("j = "); scanf("%d", &j);
    
    for (i = 1; i <= j; i++)
    {
        if (i == 6)
            continue;
        printf("%d ", i);
    } 
    putchar('\n');
    puts("xxxxxyyyyyy");
    
    return 0;
}

 continue语句则是仅仅跳出“6”的那一次执行过程。

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14683218.html