(C语言)循环结构
1.for
for(A;B;C)
{
D;
}
A表达式只会执行一次
B是执行条件
C是一条语句
执行顺序:A->B(条件)->{D}->C->B(条件)->{D}->C…
//1+2+3+....+100
int i = 1;
int sum = 0;
//for()后面不能加分号
for (i = 1;i<=100;i++)
{
sum += i;
}
printf("%d\n", sum);
2.while
//1+2+3+....+100
int i = 1;
int sum = 0;
//while(条件)条件为真就执行,为假结束循环
// 先判断再执行
//注:while()后面不要加分号
while (i<=100)
{
sum = sum + i;
i++;
}
printf("%d\n", sum);
3.do{
}while();
//1+2+3+....+100
int i = 1;
int sum = 0;
//先执行语句再判断
//while()后面加分号
do {
sum += i;
i++;
} while (i<=100);
printf("%d\n", sum);
4.嵌套循环
//嵌套循环
int n = 0;
int m = 0;
for (n = 0; n < 2; n++)
{
for (m = 0; m < 3; m++)
{
printf("i=%d j=%d\n", n, m);
}
}