AI智能
改变未来

C#入门第五课循环结构


循环结构

while循环结构

while(条件表达式)
{
}
条件表达为真,执行循环体,一旦表达式为假,循环停止。
例如:

int num1 = 0;int a = 100;while (a <= 10000){int a1 = a % 10;int a2 = a / 10 % 10;int a3 = a / 10 / 10 % 10;int a4 = a / 10 / 10 / 10 % 10;int a5 = a / 10 / 10 / 10 / 10 % 10;int q = a1 + a2 + a3 + a4 + a5;if (q == 7){num1 += 1;}a += 1;}Console.WriteLine(num1);int b = 1;int num2 = 0;while (b <= 100){b += 1;if (b % 2 == 0){Console.Write(b+\" \");}}Console.WriteLine();int c = 1;int num3 = 0;while (c <= 100){num3 = num3 + c;c += 1;}Console.WriteLine(num3);

break
switch语句中跳出switch语句
循环体中用来跳出循环(通常与if一起用)

int a = 8;int b = new Random().Next(100, 300);while (true){int c = new Random().Next(a - 2, a + 3);b -= c;Console.WriteLine(\"敌人受到了\" + c + \"点伤害\");if (b <= 0){break;}}
while (true){int a = Convert.ToInt32(Console.ReadLine());if (a < 0){Console.WriteLine(\"结束\");break;}}

continue
在循环中的作用:结束本次循环,后面的代码不再执行,进入下一次循环(通常与if连用)

int a = 1;while (a <= 100){if (a % 3 == 0){a++;continue;}Console.WriteLine(a);a++;}

do while循环

不常用,先执行循环体,再判断循环条件,直到条件不满足时候,循环结束。

int sum = 0;int a = 1;do{sum = sum + a;a++;}while (sum <= 10000);Console.WriteLine(sum-a);Console.WriteLine(a-1);

for循环

for(循环变量初始化;循环条件;循环增量)
{
}
循环条件为真,执行循环体。
循环条件为假,跳出循环。

int num = 0;for (int a = 1; a <= 100; a++){num += a;}Console.WriteLine(num);int num = 0;
for(int a = 1; a <= 100; a++){if (a % 7 != 0){int a1 = a % 10;int a2 = a / 10 % 100;int a3 = a / 100;if (a1 != 7 && a2 != 7 && a3 != 7){Console.WriteLine(a+\" \");}}}
static void Main(string[] args){for(int a = 1; a < 10; a++){for(int b = 1; b <= a; b++){Console.Write(\"{0}x{1}={2} \",a,b,a*b);}Console.WriteLine();}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#入门第五课循环结构