07day循环语句
07day循环语句
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _07day循环语句 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 /* 局部变量定义 */ 14 int a = 10; 15 16 /* while 循环执行 */ 17 while (a < 20) 18 { 19 Console.WriteLine("a 的值: {0}", a); 20 a++; 21 } 22 Console.ReadLine(); 23 24 /* for 循环执行 */ 25 for (a=15; a < 20; a = a + 1) 26 { 27 Console.WriteLine("a 的值: {0}", a); 28 } 29 Console.ReadLine(); 30 31 int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 }; 32 foreach (int element in fibarray)//依次迭代数组内的整型,迭代一次执行一次循环语句 33 { 34 Console.WriteLine(element);//每次循环需要执行的内容 35 } 36 Console.ReadLine(); 37 38 39 // 类似 foreach 循环 40 for (int i = 0; i < fibarray.Length; i++)//确定i的值, 41 { 42 Console.WriteLine(fibarray[i]);//输出数组中第i个值 43 } 44 Console.ReadLine(); 45 46 47 // 设置集合中元素的计算器 48 int count = 0; 49 foreach (int element in fibarray) 50 { 51 count += 1; 52 Console.WriteLine("Element #{0}: {1}", count, element);//count值反映了循环主体的执行次数,从1开始代表了数组中第一个整型,依次往后 53 } 54 Console.WriteLine("Number of elements in the array: {0}", count); 55 Console.ReadLine(); 56 57 /* do 循环执行do while 循环至少循环一次实例 */ 58 do 59 { 60 Console.WriteLine("a 的值: {0}", a); 61 a = a + 1; 62 } while (a < 20); 63 Console.ReadLine(); 64 65 /* 局部变量定义 */ 66 int k, j; 67 //嵌套 for 循环 68 for (k = 2; k < 100; k++) 69 { 70 for (j = 2; j <= (k / j); j++) 71 if ((k % j) == 0) break; // 如果找到,则不是质数 72 if (j > (k / j)) 73 Console.WriteLine("{0} 是质数",k); 74 } 75 Console.ReadLine(); 76 77 /* while 循环执行 */ 78 while (a < 20) 79 { 80 Console.WriteLine("a 的值: {0}", a); 81 a++; 82 if (a > 15) 83 { 84 /* 使用 break 语句终止 loop */ 85 break; 86 } 87 } 88 Console.ReadLine(); 89 90 /* do 循环执行 */ 91 do 92 { 93 if (a == 15) 94 { 95 /* 跳过迭代 */ 96 a = a + 1; 97 continue; 98 } 99 Console.WriteLine("a 的值: {0}", a); 100 a++; 101 102 } while (a < 20); 103 104 Console.ReadLine(); 105 } 106 } 107 }