C# For Loop with Break and Continue
In C#, the break
and continue
statements are used to alter the flow of loops. The break
statement terminates the loop entirely, while the continue
statement skips the rest of the current iteration and proceeds to the next one. These statements can be particularly useful within for
loops to control execution based on conditions.
Key Topics
1. Using Break in a For Loop
Example: Exiting Loop Early
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break; // Exit the loop when i is 3
}
Console.WriteLine(i);
}
Console.WriteLine("Loop exited.");
Output:
2
Loop exited.
Code Explanation: When i
reaches 3
, the break
statement terminates the loop. Only numbers 1
and 2
are printed.
2. Using Continue in a For Loop
Example: Skipping an Iteration
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // Skip the rest of the loop when i is 3
}
Console.WriteLine(i);
}
Output:
2
4
5
Code Explanation: When i
is 3
, the continue
statement skips to the next iteration, so 3
is not printed.
3. Break vs. Continue
The break
statement exits the loop entirely, while the continue
statement skips the current iteration but continues with the loop.
Example: Comparing Break and Continue
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
// Uncomment one of the following:
// break;
// continue;
}
Console.WriteLine(i);
}
Explanation: Depending on whether break
or continue
is used, the loop's behavior changes. Using break
stops the loop at i = 3
, while continue
skips i = 3
but continues the loop.
4. Best Practices for Break and Continue
- Use
break
to exit a loop when a certain condition is met, avoiding unnecessary iterations. - Use
continue
to skip specific iterations without terminating the loop. - Avoid overusing
break
andcontinue
as they can make code harder to read. - Ensure that the use of these statements does not lead to unexpected behavior or infinite loops.
Key Takeaways
- The
break
statement exits a loop immediately. - The
continue
statement skips the rest of the current iteration and moves to the next one. - These statements provide control over loop execution based on conditions.
- Proper use of
break
andcontinue
can optimize performance by avoiding unnecessary iterations. - Understanding their effects is crucial to prevent logic errors in loops.