1、while循环
*基本语法格式
举例:
(1)打印1--10的数字
#include<stdio.h>
int main()
{
int n = 1;
while (n <= 10)
{
printf("%d ", n);
n++;
}
return 0;
}
(2)打印10--1的数字
#include<stdio.h>
int main()
{
int n = 10;
while (n > 0)
{
printf("%d ", n);
n--;
}
return 0;
}
(3)输入一个数字,将它逆序打印。
#include<stdio.h>
int main()
{
int n = 0;
scanf("%d", &n);
while (n)
{
printf("%d ", n % 10);
n /= 10;
}
return 0;
}
2、for循环
*基本语法格式
举例:
(1)打印1--10的数字
#include<stdio.h>
int main()
{
int n = 1;
for (n = 1; n <= 10; n++)
{
printf("%d ", n);
}
return 0;
}
(2)打印10--1的数字
#include<stdio.h>
int main()
{
int n = 10;
for (n = 10; n > 0; n--)
{
printf("%d ", n);
}
return 0;
}
很明显,这两种代码是有联系的,联系在哪里呢?我们用打印1--10的数字代码来举例:
在while循环中
在for循环中
这下两种代码的联系就显而易见了。很明显,for循环在形式上相对于while循环来说会更好一点,我们可以认为for循环是while循环的优化版,但是我们要分情况。
3、do-while循环
*基本语法格式
举例:
(1)打印1--10
#include<stdio.h>
int main()
{
int n = 1;
do
{
printf("%d ", n);
n++;
} while (n <= 10);
return 0;
}
在这里我们要注意一点:do-while循环不论条件是否满足循环肯定会执行一次的。但是while循环和for循环要是条件不满足便不会执行,这也是do-while循环与他们的区别。
剩下的两个我们就可以举一反三了,在这里我们就不再编写了。
我们已经学习完了循环分支语句,我们接下来再来学习在循环分支语句中的两个关键字。
4、break和continue
(1)break:用于永久的终止循环,只要break执行,就会跳出本次循 环,继续往后执行。
(2)continue:用于跳出本次循环,执行本次循环后面的代码。
我们用代码来演示:
首先,我们用while循环来演示break的作用:
假设有5杯水,小明喝了3杯就够了,不想继续喝了,在这个时候我们就用break。
#include<stdio.h>
int main()
{
int n = 1;
while (n <= 5)
{
if (n == 4)//这里是4,不是3,代表喝完第三杯就好了,不喝第四杯了。
break;
printf("第%d杯\n", n);
n++;
}
return 0;
}
我们再用while循环来演示continue的作用,我们打印1--10的数字并且不打印4,这个时候我们就需要用continue了。
#include<stdio.h>
int main()
{
int n = 0;
while (n < 10)//这里是 < 4;不是 <= 4
{
n++;
if (n == 4)
continue;
printf("%d ", n);
}
return 0;
}
接下来,我们用for循环来演示break的作用
#include<stdio.h>
int main()
{
int n = 1;
for (n = 1; n <= 10; n++)
{
if (n == 5)
break;
printf("%d ", n);
}
return 0;
}
我们看着这个代码有什么感觉呢?能不能知道它的意义呢?
很明显,在打印1--10的时候,打印1--4就可以了,其余后面的就不再打印了
同样的,我们把这个代码中的break换成continue,打印的结果是什么呢?
#include<stdio.h>
int main()
{
int n = 1;
for (n = 1; n <= 10; n++)
{
if (n == 5)
continue;
printf("%d ", n);
}
return 0;
}
输出结果是:1 2 3 4 6 7 8 9 10
是的,这个代码是跳过5来打印1--10之间其他的数字。这下我们就理解了break和continue的作用了,但是我们在做题的时候要具体情况具体对待,还要记住在while循环和for循环中的continue的作用是不同的,因为在while循环中continue执行是去到判断部分,在for循环中是去到调整部分。
我们用下面的代码来说明:
#include<stdio.h>
int main()
{
int n = 1;
while (n <= 10)
{
if (n == 5)
continue;
printf("%d", n);
n++;
}
return 0;
}