C# Break ,Continue and Goto Statements
C# Break
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when i is equal to 5:
// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler
using System;
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
Output :
0
1
2
3
4
C# Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 6:
for (int i = 0; i < 10; i++)
{
if (i == 6)
{
continue;
}
Console.WriteLine(i);
}
Output
0
1
2
3
4
5
7
8
9
C# goto(Jump Statement)
The goto is C# unconditional jump statement. When encountered, program flow jumps to the location specified by the goto.It can be used to transfer control from deeply nested loop or switch case label.On the other side, it is avoided to use goto statement in C# because it makes the program complex.
The goto requires a label of operation. A label is a valid C# identifier followed by colon.
There are different-different ways for using Goto statement such as:
1.We can write code for loop with the help of goto statement
int x = 1; Loop: x++; if (x < 50) { goto loop;
2.The goto can also be used to jump to a case or default statement in a switch
Here is the example
string Fruit = "Banana";
switch (Fruit)
{
case "Apple":
MessageBox.Show(Fruit + " is the delecious fruit");
break;
case "Chair":
MessageBox.Show(Fruit + " is the delecious fruit");
break;
case "Banana":
goto case "Apple";
case "Table":
goto case "Chair";
default:
MessageBox.Show("Select valid option");
break;
}
In this case, case and default statements of a Switch are labels thus they can be targets of a goto. Nevertheless, the goto statement must be executed from within the switch. that is we can't use the goto to jump into switch statement .
Example:
using System;
public class GotoExample
{
public static void Main(string[] args)
{
ineligible:
Console.WriteLine("You are not eligible to race!");
Console.WriteLine("Enter your age:\n");
int age = Convert.ToInt32(Console.ReadLine());
if (age < 18){
goto ineligible;
}
else
{
Console.WriteLine("You are eligible to race!");
}
}
}
Output
You are not eligible to race!
Enter your age:
Comments
Post a Comment