一,while循环
1.代码
#include <stdio.h>
int main(){
int i = 0;
while(i<3000){
printf("%d. I miss you \n",i+1);
i++;
}
return 0;
}
2.结果
二,死循环
while(表达式) 表达式一直为true,循环一直执行
1.代码
#include <stdio.h>
int main(){
while(1){
int year;
printf("\n请输入一个年份:");
scanf("%d",&year);
if((year%100==0 && year%4!=0)||year%400==0){
printf("%d 是闰年\n",year);
} else {
printf("%d 不是闰年\n",year);
}
}
return 0;
}
2.结果
3.break跳出循环
代码
#include <stdio.h>
int main(){
while(1){
int year;
printf("\n请输入一个年份:(0表示退出)");
scanf("%d",&year);
if(year == 0){
break;
}
if((year%100==0 && year%4!=0)||year%400==0){
printf("%d 是闰年\n",year);
} else {
printf("%d 不是闰年\n",year);
}
}
return 0;
}
三,do-while 语句(先执行后判断,至少执行 1 次)
1.代码
#include <stdio.h>
#include <string.h> // 用于strcmp函数(字符串比较)
int main() {
char password[20];
char correct_pwd[] = "123456";
do {
printf("请输入密码:");
scanf("%s", password); // 输入密码(循环体至少执行1次)
} while (strcmp(password, correct_pwd) != 0); // 条件:密码不匹配则继续
printf("密码正确,登录成功!\n");
return 0;
}
2.结果:
四,循环变量 i j k
#include <stdio.h>
//循环变量
int main(){
int i = 10;//循环变量i j k
while(i>3){
printf("%d I miss you \n",i);
i--;//i++ === i= i+1 9 5 7
}
return 0;
}
五,求累加
1.示例
s=1+2+3+4+5...+100;
#include <stdio.h>
int main(){
int s = 0 ;
int i = 1 ;
while(i <= 100){
printf("%d \n",i);
s = s + i;
i++;
}
printf("%d \n",s);
return 0;
}
2.作业
(1)奇数累加 s = 1 + 3 + 5 + 7 +...+ 99
(2)偶数累加 s = 2 + 4 + 6 + 8 +...+ 100
(1)s = 1 + 3 + 5 + 7 + ... + 99;
代码
#include <stdio.h>
int main(){
int s = 0 ;
int i = 1 ;
while(i <= 100){
printf("%d \n",i);
s = s + i;
i+=2;
}
printf("1 + 3 + 5 + 7 + ... + 99的和为:%d \n",s);
return 0;
}
结果
(2)s = 2 + 4 + 6 + 8 + ... + 100;
代码
#include <stdio.h>
int main(){
int s = 0 ;
int i = 2 ;
while(i <= 100){
printf("%d \n",i);
s += i;
i +=2;
}
printf("2 + 4 + 6 + 8 + ... + 100的和为:%d \n" , s);
return 0;
}
结果