Vòng lặp for thực thi chuỗi câu lệnh nhiều lần và quản lý biến lặp một cách gọn gàng.
Ví dụ
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] n = new int[10];
int i, j;
// Khởi tạo mảng bằng for
for (i = 0; i < 10; i++)
n[i] = i + 100;
// Xuất mảng bằng for
for (j = 0; j < 10; j++)
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
// Truy cập phần tử thứ 3 (index 2)
int a = n[2];
Console.WriteLine("Phần tử thứ 3: " + a);
Console.ReadKey();
}
}
}
Kết quả
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Phần tử thứ 3: 102
Cấu trúc for loop
for (init; condition; increment)
{
// body
}
init: Khởi tạo biến lặp (chạy 1 lần)condition: Điều kiện tiếp tục (kiểm tra mỗi lần)increment: Cập nhật biến lặp (chạy sau mỗi lần lặp)
Các biến thể
// Lặp ngược for (int i = arr.Length - 1; i >= 0; i--) // Bước nhảy 2 for (int i = 0; i < arr.Length; i += 2) // Nhiều biến for (int i = 0, j = arr.Length - 1; i < j; i++, j--) // Vô hạn (break bên trong) for (int i = 0; ; i++)
Ưu điểm for vs foreach: Có chỉ số, có thể sửa mảng, lặp ngược, bước nhảy tùy ý.