Exit For Loop C#

This guide is part of a series. For more lessons, visit the C# for Beginners tutorial.

In this tutorial, you will learn how to exit a For loop in C#. You can break a For loop using the break; statement.

Breaking a For Loop

By now, you understand the syntax of a For loop in C#.

for (int i = 0; i < length; i++) { }

This loop will run as long as long as the conditions in the conditions section (i < length) are true. Suppose, however, that you want your loop to run 10 times, unless some other conditions are met before the looping finishes.

If you want to break out of your loop early, you are in luck. The break; statement in C# can be used to break out of a loop at any point.

using System;
 
namespace ForLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
                if (i == 7)
                {
                    Console.WriteLine("We found a match!");
                    break;
                }
            }
            Console.ReadLine();
 
        }
    }
}

In this example, we have added an if statement inside our loop (Line 12) to check for a specific condition. If that condition is met, the program will execute the code inside the code block on Lines 13-16. Line 15 is part of that code block and contains the break; statement. Once this statement is executed, the program will break out of the for loop and jump to Line 18.

With the simple break; statement, you can exit your loop before it is scheduled to end and continue with the next line of code after the loop code block.

The Bottom Line

In this tutorial, you learned how to break out of a for loop. This is useful when using a loop for data manipulation or for finding matching items. If you have any questions, let me know in the comments!


Was this article helpful? Share it with your friends:

Share on email
Share on facebook
Share on twitter
Share on reddit

Leave a Comment

Looking for more?

You have visited our site before, and we appreciate you!

If you found the tutorials helpful, enter your email address for more free C# tips and tricks.

Can't get enough C#?

Enter your email address for more free C# tutorials and tips.