- 用for循环反转数组元素的顺序:
int[] numbers = { 1, 2, 3, 4, 5 }; for (int i = 0; i < numbers.Length / 2; i++) { int temp = numbers[i]; numbers[i] = numbers[numbers.Length - 1 - i]; numbers[numbers.Length - 1 - i] = temp; }
- 用for循环输出九九乘法表:
for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { Console.Write($"{i} * {j} = {i * j}\t"); } Console.WriteLine(); }
- 用for循环实现冒泡排序:
int[] numbers = { 5, 2, 8, 1, 3 }; for (int i = 0; i < numbers.Length - 1; i++) { for (int j = 0; j < numbers.Length - 1 - i; j++) { if (numbers[j] > numbers[j + 1]) { int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } }
这些是一些在C#中使用for循环的创造性应用,展示了for循环在不同场景中的灵活性和多样性。