在 C# 中,while 循环用于多次迭代程序的一部分。如果迭代次数不固定,建议使用while循环而不是for循环。
while(condition){
//要执行的代码
}流程图:

让我们看一个简单的 while 循环来打印表格 1 的例子。
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=10)
{
Console.WriteLine(i);
i++;
}
}
}输出:
1 2 3 4 5 6 7 8 9 10
在C#中,我们可以在另一个while循环中使用while循环,它被称为嵌套while循环。当外部循环执行一次时,嵌套的while循环将完全执行。
让我们看一个 C# 编程语言中嵌套 while 循环的简单示例。
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
Console.WriteLine(i+" "+j);
j++;
}
i++;
}
}
}输出:
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
我们还可以通过传递true作为测试条件来创建无限 while 循环。
using System;
public class WhileExample
{
public static void Main(string[] args)
{
while(true)
{
Console.WriteLine("不定式 While 循环");
}
}
}输出:
不定式 While 循环 不定式 While 循环 不定式 While 循环 不定式 While 循环 不定式 While 循环 Ctrl+C