Breaking out of a 'for' loop [closed]

淺唱寂寞╮ 提交于 2019-12-13 09:54:22

问题


I'm supposed to use this code

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;
}

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.

Here my whole program:

#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


回答1:


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);
    }
}

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.

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++)



回答2:


It would be in your second for block, so above or below the print statement. It's the only place it can go given the scope of the variables.




回答3:


The break in the inner loop will bring you out of the inner for loop when i == 2 and j == 1, thus it won't run the function printf("Running i=%d j=%d\n", i, j);

It is continuing looping, because the code still needs to run the loops until both i and j are less than 4.



来源:https://stackoverflow.com/questions/16555952/breaking-out-of-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!