for 循环
在C#中,for和foreach循环是用于迭代集合或数组的两种常见方式。
一个 for 循环是一个允许编写一个执行特定次数的循环的重复控制结构。
for循环是C#中最常用、最灵活的一种循环结构,for循环既能够用于循环次数已知的情况,又能用于循环次数未知的情况,本节将对for循环使用进行详细的讲解。
for 循环的语法:
for ( init; condition; increment )
{
statement(s);
}
或者
for (初始化; 条件; 迭代) //for循环通常用于迭代一定次数的语法
{
// 循环体
}
for 循环的控制流程:
- init 会首先被执行,且只会执行一次。这一步允许您声明并初始化任何循环控制变量。您也可以不在这里写任何语句,只要有一个分号出现即可。
- 接下来,会判断 condition。如果为真,则执行循环主体。如果为假,则不执行循环主体,且控制流会跳转到紧接着 for 循环的下一条语句。
- 在执行完 for 循环主体后,控制流会跳回上面的 increment 语句。该语句允许您更新循环控制变量。该语句可以留空,只要在条件后有一个分号出现即可。
- 条件再次被判断。如果为真,则执行循环,这个过程会不断重复(循环主体,然后增加步值,再然后重新判断条件)。在条件变为假时,for 循环终止。
for与while可以对比一下
完整示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForLoop1
{
internal class Program
{
static void Main(string[] args)
{
/* for 循环执行 */
for (int a = 10; a < 20; a = a + 1)
{
Console.WriteLine("a 的值: {0}", a);
}
}
}
}
模拟场景:例如for循环迭代一个数组并打印出每个元素。
完整示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForLoop2
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
}
}
foreach
C# foreach 循环,使用foreach可以迭代数组或者一个集合对象。
foreach循环语法:
foreach (元素类型 变量名 in 集合或数组)
{
// 循环体
}
和FOR循环对比完整示例代码(更加简洁):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForeachLoop1
{
internal class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
}//哪个更加简洁?
以下完整示例代码有三个部分:
- 通过 foreach 循环输出整型数组中的元素。
- 通过 for 循环输出整型数组中的元素。
- foreach 循环设置数组元素的计算器。
完整示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForeachLoop
{
internal class Program
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
// 类似 foreach 循环
for (int i = 0; i < fibarray.Length; i++)
{
System.Console.WriteLine(fibarray[i]);
}
System.Console.WriteLine();
// 设置集合中元素的计算器
int count = 0;
foreach (int element in fibarray)
{
count += 1;
System.Console.WriteLine("Element #{0}: {1}", count, element);
}
System.Console.WriteLine("Number of elements in the array: {0}", count);
}
}
}