Algorithm
In C#, the break
statement is used to exit a loop prematurely. It is typically used in for
, while
, and do-while
loops to terminate the loop's execution based on a certain condition. The break
statement immediately ends the loop and transfers control to the statement following the loop.
Code Examples
#1 C# Programming break statement with for loop
Code -
C# Programming
using System;
namespace CSharpBreak {
class Program {
static void Main(string[] args) {
for (int i = 1; i < = 4; ++i) {
// terminates the loop
if (i == 3) {
break;
}
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
2
#2 C# Programming break statement with while loop
Code -
C# Programming
using System;
namespace WhileBreak {
class Program {
static void Main(string[] args) {
int i = 1;
while (i < = 5) {
Console.WriteLine(i);
i++;
if (i == 4) {
// terminates the loop
break;
}
}
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
2
3
#3 break Statement with Nested Loop in C# Programming
Code -
C# Programming
using System;
namespace NestedBreak {
class Program {
static void Main(string[] args) {
int sum = 0;
for(int i = 1; i < = 3; i++) { //outer loop
// inner loop
for(int j = 1; j < = 3; j++) {
if (i == 2) {
break;
}
Console.WriteLine("i = " + i + " j = " +j);
}
}
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
i = 1 j = 2
i = 1 j = 3
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3
#4 break with foreach Loop in C# progrram
Code -
C# Programming
using System;
namespace ForEachBreak {
class Program {
static void Main(string[] args) {
int[] num = { 1, 2, 3, 4, 5 };
// use of for each loop
foreach(int number in num) {
// terminates the loop
if(number==3) {
break;
}
Console.WriteLine(number);
}
}
}
}
Copy The Code &
Try With Live Editor
Output
2
#5 break with Switch Statement in C# Programming
Code -
C# Programming
using System;
namespace ConsoleApp1 {
class Program {
static void Main(string[] args) {
char ch='e';
switch (ch) {
case 'a':
Console.WriteLine("Vowel");
break;
case 'e':
Console.WriteLine("Vowel");
break;
case 'i':
Console.WriteLine("Vowel");
break;
case 'o':
Console.WriteLine("Vowel");
break;
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
}
}
}
}
Copy The Code &
Try With Live Editor
Output
Demonstration
C# Programming break Statement