GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C# - Break Statement
Selected Reading
C# - Break StatementC# break StatementThe break statement in C# has following two usage −
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. SyntaxThe syntax for a break statement in C# is as follows − break; Flow Diagram
Using break Statement with while LoopIn this example, we terminate the while loop after it reaches 15 − using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}
OutputWhen the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 Using break Statement with for LoopIn this example, we terminate the for loop if we find the first even number. We then display the first even number − using System;
class BreakExample {
static void Main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
Console.WriteLine("First even number found: " + i);
break;
}
Console.WriteLine("Checking number: " + i);
}
Console.WriteLine("Loop terminated after finding the first even number.");
}
}
OutputThe above code produces the following Output − Checking number: 1 First even number found: 2 Loop terminated after finding the first even number. Advertisements
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |