C# Break and Continue Statements
In C#, the break
and continue
statements are used to alter the flow of execution of loops such as the for
, while
, and do-while
loops. These statements provide more control over how the loops execute and can be used to optimize code and avoid unnecessary processing.
The Break Statement
The break
statement is used to immediately terminate a loop and continue with the execution of the program. When a break
statement is encountered inside a loop, the control of the program is immediately transferred to the statement following the loop.
Here's an example that demonstrates the use of break
statement inside a for
loop:
1for (int i = 0; i < 10; i++) 2{ 3 if (i == 5) 4 { 5 break; 6 } 7 Console.WriteLine(i); 8}
In this example, the for
loop iterates from 0
to 9
. When the value of i
becomes 5
, the break
statement is encountered, and the loop is immediately terminated. The statement Console.WriteLine(i)
is never executed for i=5
. The output of this program will be:
10 21 32 43 54
The break
statement can also be used inside a switch
statement to exit the switch early:
1int number = 3; 2switch (number) 3{ 4 case 1: 5 Console.WriteLine("One"); 6 break; 7 case 2: 8 Console.WriteLine("Two"); 9 break; 10 case 3: 11 Console.WriteLine("Three"); 12 break; 13 case 4: 14 Console.WriteLine("Four"); 15 break; 16 default: 17 Console.WriteLine("Unknown"); 18 break; 19}
In this example, the switch
statement checks the value of the number
variable. When number
is 3
, the statement Console.WriteLine("Three")
is executed, and the break
statement is encountered, causing the switch statement to be exited.
The Continue Statement
The continue
statement is used to skip the remaining statements in the current iteration of the loop and proceed with the next iteration of the loop.
Here's an example that demonstrates the use of continue
statement inside a for
loop:
1for (int i = 0; i < 10; i++) 2{ 3 if (i == 5) 4 { 5 continue; 6 } 7 Console.WriteLine(i); 8}
In this example, the for
loop iterates from 0
to 9
. When the value of i
becomes 5
, the continue
statement is encountered, and the remaining statements in the current iteration are skipped. The value of i
is never printed when i=5
. The output of this program will be:
10 21 32 43 54 66 77 88 99
The continue
statement can also be used inside a while
loop:
1int i = 0; 2while (i < 10) 3{ 4 i++; 5 if (i % 2 == 0) 6 { 7 continue; 8 } 9 Console.WriteLine(i); 10}
In this example, the while
loop iterates from 1
to 10
. When the value of i
is even, the continue
statement is encountered, and the remaining statements in the current iteration are skipped. The output of this program will be:
11 23 35 47 59