Break from loop (repeating)


#1

Hello friends , when i was woking in mBlock in programming i found a problem to beak from a repeating loop if the condition is not achieved for exemple:
int C=4; int a = 0; for (int i =100; i > 0; i--) { if (C == 5) { a++; } else{ break; } }

for each i from 100 to 1 do:
if C=5 add 1 to a
if not exit that loop only (not all the program)

i wish to find that in mblock program or to add it so soon (if doesn’t exists) because it helps a lot.

that was a simple exemple I hope those who have experience in programming to understand me or even others to help me. thanks all :expressionless:


#2

Are you programming in Scratch or C? The mBlock environment uses Scratch and is a graphical language. The Arduino environment that is embedded in mBlock uses C, a text-based language. If the latter, I see a few oddities in your code:

int a = 1;
int a = 0;
for (int i = 100; i > 0; i - 1) {
    if C == 5 {
        a++;
    }
    else {
        break;
    ]
}

You declare ‘a’ as an integer and immediately redeclare it as an integer. This will cause a compiler error.

You do not declare or initialize ‘C’. This will cause a compiler error.

A more idiomatic way to write the for-loop is:

for (int i = 100; i > 0; i--)

Your test:

if C == 5 {
    a++;
}
else {
    break;
}

will cause a compiler error because the conditional part, C == 5, is not surrounded by parentheses. Also, because C is never declared it will cause a compilation error. I would also observe that ‘C’ is never modified in the code, so it would never change from its originally declared value.

Regards,

Chuck


#3

Thank you a lot mr.Chuck but my problem isn’t in the code but in the mblock program i did not find the break block to quit from executing a loop i wish that you 're anderstanding me . the code that i wrote in my question is just an exemple to anderstand the concept of the commande break it is not executable Code
But thank you for your note


#4

Hi @Slimane,

If you are referring to the graphical version of mBlock, you are correct, there is no “break” command. You will need to use a flag as part of the exit conditions for the loop (see example below).

I should note that with the program as-is, the exit flag will be called on the first iteration because C is being set to 4 and is never changed, but you likely knew that. :slight_smile:


#5

Thank you @chuckmcknight !! Problem Solved !! :grinning: