if 语句
int a = 5;
int b = 3;
if (a + b > 10)
Console.WriteLine("The answer is greater than 10");
else
Console.WriteLine("The answer is not greater than 10");
&&
表示“且”。 也就是说,两个条件必须都为 true
||
表示“或”
while
语句检查条件,并执行 while
后面的语句。 除非条件为 false,否则它会重复检查条件,并重复执行这些语句
int counter = 0;
while (counter < 10)
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
}
while
循环先测试条件,然后再执行 while
后面的代码。 do
... while
循环先执行代码,然后再检查条件。 代码如下所示:
int counter = 0;
do
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
} while (counter < 10);
使用 for 循环
for(int counter = 0; counter < 10; counter++)
{
Console.WriteLine($"Hello World! The counter is {counter}");
}
第一部分是 for 初始值设定项:int counter = 0;
声明 counter
是循环变量,并将它的初始值设置为 0
。
中间部分是 for 条件:counter < 10
声明只要计数器值小于 10,此 for
循环就会继续执行。
最后一部分是 for 迭代器:counter++
指定在执行 for
语句后面的代码块后,如何修改循环变量。 在此示例中,它指定 counter
应在代码块每次执行时递增 1。
列循环
for (char column = 'a'; column < 'k'; column++)
{
Console.WriteLine($"The column is {column}");
}