突破"for"循环 [英] Breaking out of a 'for' loop

查看:78
本文介绍了突破"for"循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用此代码

for (i=1; i<4; i++)
{
    for (j=1; j, 4; j++)
    {
        printf("Running i=%d j=%d\n", i, j);
    }
}

...使用此代码可以使其脱离循环

... with this code to break it out of its loop

if (i==2 && j ==1) {
    printf("Break inner loop when i=%d and j=%d\n", i, j);
    break;
}

我的教科书说要在内部循环块的最开始插入此break语句.我不知道那是哪里!我已经尝试了很多地方,但仍然无法弄清.

My textbook said to insert this break statement at the very beginning of the inner loop block. I don't know where that is! I've tried a lot of places already and still can't figure it out.

这是我的整个程序:

#include <stdio.h>

int main()
{
    int i, j;

    for (i=1; i<4; i++)
    {
        for (j=1; j,4; j++)
            if (i==2 && j ==1) {
                printf("Break inner loop when i=%d and j=%d\n", i, j);
                break;
            }
            printf("Running i=%d j=%d\n", i, j);

        }
    }
    return 0;
}


我知道了:它有错字


I figured it out: it had a typo

推荐答案

内循环块的开始紧接在第二个for上的{之后:

The beginning of the inner-loop block is just after the { on the second for:

for(i=1;i<4;i++)
{
    for(j=1;j,4;j++)
    {
        // <<<--- They mean here.
        printf("Running i=%d j=%d\n", i, j);
    }
}

请注意,break仅会跳出内循环.外循环将再次出现.如果您需要突破两个循环,则需要添加某种标记.

Note that the break will only break out of the inner loop. The outer loop will go around again. If you need to break out of both loops you will need to add a flag of some sort.

刚注意到,您的内循环中有一个错字,它实际上是有效的C(逗号运算符).应该是<:

Just noticed that you have a typo in your inner loop that is actually valid C (the comma operator). It should have been <:

   for(j=1;j<4;j++)

这篇关于突破"for"循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆