In this article am going to explain to of the
most useful concepts of C#, these are also called loops. I’ll explain and
differentiate between them through an example.
Break
Statement
Break statement breaks out of the loop at current point or we
can say that it terminates the loop condition.
It is represented by break;
It is represented by break;
Continue
Statement
Continue statement jumps out of the current loop condition
and jumps back to the starting of the loop code.
It is represented by continue;
It is represented by continue;
Example
| Break vs Continue
In this example am showing functioning of
both the statements together, afterwards I’ll explain them one by one with
their functionality.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello
{
class Program
{
static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
if (i == 5)
continue;
if (i == 8)
break;
Console.WriteLine("value is" +i);
}
Console.ReadLine();
}
}
}
Output Window
Explanation
In this example the out is from 0 to 7 excepting 5, 8, 9 ?
CASE: 1 It is because in the first case-
if
(i == 5)
continue;
Means it will skip the current loop and jumps to the top of
the loop, so there is no 5 in the
output window.
CASE:
2 In second cases-
if
(i == 8)
break;
It will terminate the loop or get out of it when value becomes 8, so there is no 8, 9 in the output window.
Now let’s do some changes in the code and see what happens,
here we go-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello
{
class Program
{
static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
if (i == 5)
continue;
// if (i == 8)
// break;
Console.WriteLine("value
is: " +i);
}
Console.ReadLine();
}
}
}
Now you can see the output.
Condition continues to flow according to the continue statement
functioning.
Now am making some other modifications, in the code snippet,
as-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello
{
class Program
{
static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
// if (i == 5)
// continue;
if (i == 8)
break;
Console.WriteLine("value
is: " +i);
}
Console.ReadLine();
}
}
}
Now you can see, it again showing from 0 to 7 and because of the break statement
condition, it’s again out of the loop so there is no 8, 9, 10
No comments:
Post a Comment