C#循环例子大总结
1: 三角形状:
for (int i = 0; i < 10; i++) { for (int j = 0; j < 10 - i; j++) { Console.Write(" "); } for (int k = 0; k < i; k++) { Console.Write("* "); } Console.WriteLine(); }
2: 空心三角形状:
for (int i = 9; i >= 0; i--) { for (int j = 0; j < i; j++) { Console.Write(" "); } for (int j = 0; j < ((9 - i) * 2 + 1); j++) { if (i == 0 || i == 9) { Console.Write("*"); } else { if (j == 0 || j == (9 - i) * 2) Console.Write("*"); else Console.Write(" "); } } Console.WriteLine(); }
3: 空心直角三角形:
for (int i = 0; i < 10; i++) { for (int j = 0; j <= i; j++) { if (i == 0 || i == 1 || i == 9) Console.Write("*"); else { if (j == 0 || j == i) Console.Write("*"); else Console.Write(" "); } } Console.WriteLine(); }
4:矩形:
for (int i = 0; i < 5; i++) { for (int j = 0; j < 10; j++) { Console.Write("*"); } Console.WriteLine(); }
5:空心矩形:
for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (i == 0 || i == 9) Console.Write("*"); else { if (j == 0 || j == 9) Console.Write("*"); else Console.Write(" "); } } Console.WriteLine(); }
6: 菱形:
for (int i = 1; i <= 10; i++) { if (i <= (10 + 1) / 2) { for (int j = 0; j < (10 + 1) / 2 - i; j++) Console.Write(" "); for (int j = 0; j < i; j++) Console.Write("* "); Console.WriteLine(); } else { for (int j = 0; j < i - (10 + 1) / 2; j++) Console.Write(" "); for (int j = 0; j < 10 + 1 - i; j++) Console.Write("* "); Console.WriteLine(); } }
7: 冒泡排序:
int temp; int[] num = { 20, 5, 8, 110, 79, 65, 23, 1, 15, 66 }; for (int i = 0; i < num.Length - 1; i++) { for (int j = 0; j < num.Length - 1 - i; j++) { if (num[j] > num[j + 1]) { temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; } } } for (int result = 0; result < num.Length; result++) { Console.Write(num[result]+" "); }
8:菲波那挈数列(//实现数字按一定的规律增长 1,1,2,3,5,8,13,21)
int x = 0, y = 1; for (int j = 1; j < 21; j++, y = x + y, x = y - x) { Console.Write(y + " "); } Console.ReadLine();
9: 三角形数字列:(//1,3,6,10,15,21)
int n1 = 1, n2 = 1; for (int i = 1; i < 11; i++) { Console.Write(n2 + " "); n2 = n1 + i + 1; n1 = n2; }
10:约瑟夫环(从第start人开始计数,以alter为单位循环记数出列,总人数为total )
int total = 17;//人数 int alter = 3;//谁的倍数退出 List<int> list = new List<int>(); for (int i = 0; i < total; i++) { list.Add(i); } int start = 1; while (list.Count > 1)//进入数数阶段 { for (int i = 0; i < list.Count; i++) { if (start % alter == 0)//判断是否为3的倍数 { Console.WriteLine("编号为{0}退出", list[i]);//显示退出的人 list.RemoveAt(i); i--;//因为退出一个人,所以向前推一; } start++;//继续数数 } } Console.WriteLine("编号为{0}留下", list[0]);
因为相信,所以我去做了......