C#: break vs continue — what is the difference in loops?
Hello everyone. I just started learning C#, and I'm confused about the break and continue statements inside loops (for, while, foreach). I understand that both somehow affect loop execution, but I can't grasp the specific difference.
For example, I have this code:
```csharp
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
```
I expected it to output numbers from 0 to 9, but it only printed 0, 1, 2, 3, 4. Why? I thought break just skips an iteration when i == 5.
And another example with continue:
```csharp
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
Console.WriteLine(i);
}
```
This code printed all numbers from 0 to 9 except 5. So continue really does skip an iteration? But then why does break behave differently?
Please explain in simple terms: what is the fundamental difference between break and continue? When should each statement be used? And are there any pitfalls?
No answers yet.
Log in to leave an answer