Skip to content

Difference between break and continue

Difference between break and continue

In C# break vscontinue are control flow statements used to alter the flow of execution within loops (such as for, while, and do-while) and switch statements. They serve different purposes and are used in different scenarios. Let us see the difference between break and continue in c# :

Difference between break and continue

break

  1. Purpose:
    • The break in c# is used to exit a loop prematurely. When encountered inside a loop or switch statement, the break statement immediately terminates the loop or exits the switch block, regardless of whether the loop’s condition is still true or not.
  2. Usage:
    • It is often used when you need to exit a loop early based on a certain condition. For example, in a for loop, you may use break to stop iterating once a specific condition is met.

Example of break:

for (int i = 0; i < 10; i++)
{
    if (i == 5)
        break; // Exit the loop when i equals 5.
    Console.WriteLine(i);
}

Output:

0
1
2
3
4

continue

  1. Purpose:
    • The continue in C# is used to skip the rest of the current iteration of the loop and pass the control to the next iteration. When encountered inside a loop, the continue statement immediately jumps to the next iteration of the loop, skipping any remaining code within the loop’s body for the current iteration.
  2. Usage:
    • It is used when you want to skip specific iterations based on a condition without prematurely terminating the entire loop. For example, in a for loop, you may use continue to skip certain values or perform specific actions only for some iterations.

Example of continue:

for (int i = 0; i < 5; i++)
{
    if (i == 2)
        continue; // Skip the iteration when i equals 2.
    Console.WriteLine(i);
}

Output:

0
1
3
4

Conclusion

In summary, break is used to exit the loop or switch statements prematurely, while continue is used to skip the current iteration and proceed with the next iteration in the loop. These statements are essential for controlling the flow of execution and tailoring the behavior of loops based on specific conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *