← C# from Scratch
Lesson 19 of 39 · 10 XP
break and continue
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
break— leave the loop immediately;continue— skip the rest of the body and go on to the next iteration.
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0) continue; // skip the even ones
if (i > 7) break; // don't go past 7
Console.Write(i + " "); // 1 3 5 7
}
break leaves only the nearest loop. The easiest way to leave nested loops at once is to move the loops
into a method and return.
Task. Read numbers, one per line. Skip negative ones, and stop at 0
(there may be more lines after it — don't read them). Print the sum and how many numbers were taken into account, separated by a space.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.