C# do-while 循环用于多次迭代程序的一部分。如果迭代次数不固定,必须至少执行一次循环,推荐使用do-while循环。
C# do-while 循环至少执行一次,因为条件是在循环体之后检查的。
do{
//code to be executed
}while(condition);
让我们看一个 C# do-while 循环打印表格 1 的简单示例。
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;
do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;
}
}输出:
1 2 3 4 5 6 7 8 9 10
在 C# 中,如果在另一个 do-while 循环中使用 do-while 循环,则称为嵌套 do-while 循环。对于每个外部 do-while 循环,嵌套的 do-while 循环都会完全执行。
让我们看一个 C# 中嵌套 do-while 循环的简单示例。
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i=1;
do{
int j = 1;
do{
Console.WriteLine(i+" "+j);
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}
}输出:
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
在 C# 中,如果在 do-while 循环中传递true,它将是不定式 do-while 循环。
do{
//code to be executed
}while(true);using System;
public class WhileExample
{
public static void Main(string[] args)
{
do{
Console.WriteLine("不定式 do-while 循环");
} while(true);
}
}输出:
不定式 do-while 循环 不定式 do-while 循环 不定式 do-while 循环 不定式 do-while 循环 不定式 do-while 循环 Ctrl+C