C#——for循环

(一)c#中for循环有两种格式:

(1)第一种形式:

for(code1;code2;code)

{

}

(2)每二种形式:

for(;;)

{

}

具体的内容看下图:

C#——for循环

(二)实例

例1:计算1到100之间(包含1、100)所有整数的和(用for循环)。

namespace for循环 { class Program { static void Main(string[] args) { //用for实现计算1到100之间(包含1、100)所有整数的和。 int sum = 0; for (int i = 1; i <= 100; i++) //<=还是<,i=0还是i=1 { sum = sum + i; } Console.WriteLine(sum); Console.ReadKey(); } } }

注意:for的终止条件 是 <= 还是 <


例2:用for实现计算200到300之间(包含200、300)所有整数的和。

实现代码:

namespace for循环 { class Program { static void Main(string[] args) { //用for实现计算200到300之间(包含200、300)所有整数的和。 int sum = 0; for (int i = 200; i <= 300; i++) { sum = sum + i; } Console.WriteLine(sum); Console.ReadKey(); } } }


例3:不断打印字符串"aaaaa"

namespace for循环 { class Program { static void Main(string[] args) { for (; ; ) //for的三段都可以省略,但是不能丢了“;” { Console.WriteLine("aaaaa"); } Console.ReadKey(); } } }


注意:for的三段都可以省略,但是不能丢了“;”,这一定也是一个死循环

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-02
  • 2021-08-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-24
  • 2021-10-24
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案