In the last topic, you learned about loops which are used to repeat a certain process some number of times.
What if we can control the way our loop operates.
In C#, we can jump out of the loop or jump to the starting condition of the loop whenever we want. We do this with the help of break
and continue
statements respectively.
C# break
break
is used to break or terminate a loop whenever we want.
Just type break;
after the statement after which you want to break the loop. As simple as that!
Remember, we had also used break
statements in switch..case
in the previous topic.
Consider an example.
using System;
class Test
{
static void Main(string[] args)
{
for(int n=1; n <= 5 ; n++)
{
Console.WriteLine("*");
if(n==2)
break;
}
}
}
In the first iteration of the loop in the above example, '*' gets printed and the condition (n == 2) is checked. Since the value of n is 1, the condition becomes false and n++
increases the value of n to 2. Again '*' gets printed and since this time the condition of if
satisfies, the break
statement terminates the loop.
Let's have a look at one more example of break.
using System;
class Test
{
static void Main(string[] args)
{
string x;
for(; ;)
{
Console.WriteLine("Enter 0 to stop");
x = Console.ReadLine();
if(x=="0")
break;
}
}
}
This is an infinite loop. To terminate this we are using break
. If a user enters 0 then the condition of if
will get satisfied and the break
statement will terminate the loop.
C# continue
continue
statement works similar to the break
statement. The only difference is that break
statement terminates the loop whereas continue
statement passes control to the conditional test i.e., where the condition is checked.
In short, it passes control to the nearest conditional test in do while
loop, or the condition of while
in while
loop, or the condition of for
in for
loop skipping the rest of the statements in the loop.
using System;
class Test
{
static void Main(string[] args)
{
int n = 1;
while(n < 10){
if (n == 5){
n = n + 1;
continue;
}
Console.WriteLine($"n = {n}");
n++;
}
}
}
In the above example, notice that n = 5 is not printed because as the value of n becomes 5, the if
condition becomes true and the statements in the body of the if
statements get executed. Thus n = n+1
increases the value of n to 6 and continue
statement passes the control to the test condition and rest of the statements are not executed (Console.WriteLine($"n = {n}")
and n++
- these two statements are not executed when n is 5 ). Then again, the iteration starts and the numbers get printed from 6 onwards.