C# loop - break vs. continue

C#LoopsEnumeration

C# Problem Overview


In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

Example:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}

C# Solutions


Solution 1 - C#

break will exit the loop completely, continue will just skip the current iteration.

For example:

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed. This here:

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

Will not execute DoSomeThingWith for i = 0, but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9.

Solution 2 - C#

A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.

break loop - looping is broken and stops.

continue loop - loop continues to execute with the next iteration.

Solution 3 - C#

break causes the program counter to jump out of the scope of the innermost loop

for(i = 0; i < 10; i++)
{
    if(i == 2)
        break;
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.

for(i = 0; i < 10; i++)
{
    if(i == 2)
        continue;

    printf("%d", i);
}

Works like this

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}

Solution 4 - C#

When to use break vs continue?

  1. Break - it's like breaking up. It's sad, you guys are parting. The loop is exited.

Break

  1. Continue - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!

Continue

(Corny stories ¯\(ツ)/¯ but helps me remember - and hopefully you too!)

Solution 5 - C#

break would stop the foreach loop completely, continue would skip to the next DataRow.

Solution 6 - C#

There are more than a few people who don't like break and continue. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-while or do-until style of loop.

I tend to use break in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.

I use continue when doing something with most elements of a list, but still want to skip over a few.

The break statement also comes in handy when polling for a valid response from somebody or something. Instead of:

Ask a question
While the answer is invalid:
    Ask the question

You could eliminate some duplication and use:

While True:
    Ask a question
    If the answer is valid:
        break

The do-until loop that I mentioned before is the more elegant solution for that particular problem:

Do:
    Ask a question
    Until the answer is valid

No duplication, and no break needed either.

Solution 7 - C#

All have given a very good explanation. I am still posting my answer just to give an example if that can help.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }
    
    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
               

Here is the output: >0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }
    
    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output: >0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed] will not be displayed as there is continue when i == 3

Solution 8 - C#

Break

Break forces a loop to exit immediately.

Continue

This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.

Solution 9 - C#

Simple answer:

Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)

Solution 10 - C#

By example

foreach(var i in Enumerable.Range(1,3))
{
    Console.WriteLine(i);
}

Prints 1, 2, 3 (on separate lines).

Add a break condition at i = 2

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        break;

    Console.WriteLine(i);
}

Now the loop prints 1 and stops.

Replace the break with a continue.

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        continue;

    Console.WriteLine(i);
}

Now to loop prints 1 and 3 (skipping 2).

Thus, break stops the loop, whereas continue skips to the next iteration.

Solution 11 - C#

Ruby unfortunately is a bit different. PS: My memory is a bit hazy on this so apologies if I'm wrong

instead of break/continue, it has break/next, which behave the same in terms of loops

Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this

a = 5
while a < 10
    a + 1
end

You can however do this

a = 5
b = while a < 10
    a + 1
end # b is now 10

HOWEVER, a lot of ruby code 'emulates' a loop by using a block. The canonical example is

10.times do |x|
    puts x
end

As it is much more common for people to want to do things with the result of a block, this is where it gets messy. break/next mean different things in the context of a block.

break will jump out of the code that called the block

next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.

def timesten
    10.times{ |t| puts yield t }
end


timesten do |x|
   x * 2
end
# will print
2
4
6
8 ... and so on


timesten do |x|
    break
    x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped

timesten do |x|
    break 5
    x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5

timesten do |x|
    next 5
    x * 2
end 
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.

So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)

Solution 12 - C#

Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.

Solution 13 - C#

To break completely out of a foreach loop, break is used;

To go to the next iteration in the loop, continue is used;

Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.

Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.

Solution 14 - C#

if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.

for(int i = 0; i < list.Count; i++){
   if(i == 5)
    i = list.Count;  //it will make "i<list.Count" false and loop will exit
}

Solution 15 - C#

As for other languages:

'VB
For i=0 To 10
   If i=5 then Exit For '= break in C#;
   'Do Something for i<5
next
 
For i=0 To 10
   If i=5 then Continue For '= continue in C#
   'Do Something for i<>5...
Next

Solution 16 - C#

Since the example written here are pretty simple for understanding the concept I think it's also a good idea to look at the more practical version of the continue statement being used. For example:

we ask the user to enter 5 unique numbers if the number is already entered we give them an error and we continue our program.

static void Main(string[] args)
        {
            var numbers = new List<int>();


            while (numbers.Count < 5)
            { 
            
                Console.WriteLine("Enter 5 uniqe numbers:");
                var number = Convert.ToInt32(Console.ReadLine());



                if (numbers.Contains(number))
                {
                    Console.WriteLine("You have already entered" + number);
                    continue;
                }



                numbers.Add(number);
            }


            numbers.Sort();


            foreach(var number in numbers)
            {
                Console.WriteLine(number);
            }


        }

lets say the users input were 1,2,2,2,3,4,5.the result printed would be:

1,2,3,4,5

Why? because every time user entered a number that was already on the list, our program ignored it and didn't add what's already on the list to it. Now if we try the same code but without continue statement and let's say with the same input from the user which was 1,2,2,2,3,4,5. the output would be :

1,2,2,2,3,4

Why? because there was no continue statement to let our program know it should ignore the already entered number.

Now for the Break statement, again I think its the best to show by example. For example:

Here we want our program to continuously ask the user to enter a number. We want the loop to terminate when the user types “ok" and at the end Calculate the sum of all the previously entered numbers and display it on the console.

This is how the break statement is used in this example:

{
            var sum = 0;
            while (true)
            {
                Console.Write("Enter a number (or 'ok' to exit): ");
                var input = Console.ReadLine();

                if (input.ToLower() == "ok")
                    break;

                sum += Convert.ToInt32(input);
            }
            Console.WriteLine("Sum of all numbers is: " + sum);
        }

The program will ask the user to enter a number till the user types "OK" and only after that, the result would be shown. Why? because break statement finished or stops the ongoing process when it has reached the condition needed.

if there was no break statement there, the program would keep running and nothing would happen when the user typed "ok".

I recommend copying this code and trying to remove or add these statements and see the changes yourself.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeibarView Question on Stackoverflow
Solution 1 - C#Michael StumView Answer on Stackoverflow
Solution 2 - C#JeremiahClarkView Answer on Stackoverflow
Solution 3 - C#SemiColonView Answer on Stackoverflow
Solution 4 - C#BenKoshyView Answer on Stackoverflow
Solution 5 - C#palmseyView Answer on Stackoverflow
Solution 6 - C#yukondudeView Answer on Stackoverflow
Solution 7 - C#Pritom NandyView Answer on Stackoverflow
Solution 8 - C#Sona RijeshView Answer on Stackoverflow
Solution 9 - C#MaltrapView Answer on Stackoverflow
Solution 10 - C#Colonel PanicView Answer on Stackoverflow
Solution 11 - C#Orion EdwardsView Answer on Stackoverflow
Solution 12 - C#cincoView Answer on Stackoverflow
Solution 13 - C#Gopesh SharmaView Answer on Stackoverflow
Solution 14 - C#Umair KhalidView Answer on Stackoverflow
Solution 15 - C#dbaView Answer on Stackoverflow
Solution 16 - C#Mostafa GhorbaniView Answer on Stackoverflow