[C#]while文にbreakで二重ループを抜けるサンプル
書式
while(条件式1) {
while(条件式2) {
if(条件){
// xxxx
break;
}
}
if(条件){
//xxxx
break;
}
}
while(条件式1) {
while(条件式2) {
if(条件){
// xxxx
break;
}
}
if(条件){
//xxxx
break;
}
}
while(条件式1) { while(条件式2) { if(条件){ // xxxx break; } } if(条件){ //xxxx break; } }
使用例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 13;
Boolean flg = false;
while (true)
{
while (true)
{
if (i == 16)
{
flg = true;
//breakは内側のwhile文のみ抜ける
break;
}
Console.WriteLine(i);
i++;
}
if (flg == true)
{ //break文で外側のwhile文を抜ける
break;
}
}
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 13;
Boolean flg = false;
while (true)
{
while (true)
{
if (i == 16)
{
flg = true;
//breakは内側のwhile文のみ抜ける
break;
}
Console.WriteLine(i);
i++;
}
if (flg == true)
{ //break文で外側のwhile文を抜ける
break;
}
}
Console.ReadKey();
}
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i = 13; Boolean flg = false; while (true) { while (true) { if (i == 16) { flg = true; //breakは内側のwhile文のみ抜ける break; } Console.WriteLine(i); i++; } if (flg == true) { //break文で外側のwhile文を抜ける break; } } Console.ReadKey(); } } }
結果
13
14
15