Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# For 循环


C# 循环

当您确切知道要循环遍历代码块多少次时,请使用 for 循环而不是 while 循环

语法

for (statement 1; statement 2; statement 3) 
{
  // code block to be executed
}

语句 1 在执行代码块之前执行(一次)。

语句 2 定义执行代码块的条件。

语句 3 在代码块执行后执行(每次)。

下面的示例将打印数字 0 到 4

示例

for (int i = 0; i < 5; i++) 
{
  Console.WriteLine(i);
}

自己尝试 »

示例解释

语句 1 在循环开始之前设置一个变量 (int i = 0)。

语句 2 定义循环运行的条件 (i 必须小于 5)。如果条件为 true,循环将重新开始,如果为 false,循环将结束。

语句 3 在循环中的代码块每次执行后增加一个值 (i++)。


另一个示例

此示例将仅打印 0 到 10 之间的偶数值

示例

for (int i = 0; i <= 10; i = i + 2) 
{
  Console.WriteLine(i);
}

自己尝试 »


嵌套循环

也可以将一个循环放在另一个循环内。这称为嵌套循环

"内循环" 将为"外循环" 的每次迭代执行一次

示例

// Outer loop
for (int i = 1; i <= 2; ++i) 
{
  Console.WriteLine("Outer: " + i);  // Executes 2 times

  // Inner loop
  for (int j = 1; j <= 3; j++) 
  {
    Console.WriteLine(" Inner: " + j); // Executes 6 times (2 * 3)
  }
}

自己尝试 »


C# 练习

用练习测试自己

练习

使用 for 循环打印 5 次"Yes"

 (int i = 0; i < 5; ) 
{
  Console.WriteLine("Yes");
}

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.