The continue
and break
statements in C# are used to control the flow of execution within loops, but they have different behaviors and purposes:
continue
statement:- The
continue
statement is used to skip the current iteration of a loop and move to the next iteration. - When a
continue
statement is encountered within a loop, the remaining code within the loop block is skipped for that iteration, and the loop proceeds with the next iteration.
Example:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
Console.WriteLine(i);
}
In this example, when i
is equal to 3, the continue
statement is triggered, and the remaining code within the loop block is
skipped for that iteration. As a result, the number 3 is not printed,
and the loop continues with the next iteration.
break
statement:
- The
break
statement is used to exit the loop prematurely. - When a
break
statement is encountered within a loop, the loop is terminated, and the program continues with the next line of code following the loop.
Example:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
break;
Console.WriteLine(i);
}
In this example, when i
is equal to 3, the break
statement is triggered, and the loop is terminated. As a result, the loop exits, and the program continues with the next line of code after the loop.
To summarize the differences:
continue
skips the remaining code within the loop block for the current iteration and proceeds with the next iteration.break
immediately exits the loop, terminating its execution, and continues with the next line of code after the loop.
Both continue
and break
statements are used to control the flow of execution within loops, but they serve different purposes. continue
allows you to skip specific iterations based on a condition, while break
allows you to exit the loop entirely based on a condition.