第12章分支与循环

1、什么是语句?

c语言中由一个分号;隔开的就是一条语句

如int a=0;

2、分支语句

if(表达式)

语句;

表达式计算结果如果为真,这个语句将会被执行

否则什么都不执行

if (表达式)

语句1;

else

语句2;

多分支

if(表达式)

语句一;

else if(表达式2)

语句2

else

语句3;

表达式1成立,执行语句1

表达式2成立,执行语句2

如果都不成立,执行语句3

switch语句(实现多分支)

switch(整形表达式)

{

语句项;

}

case 整型常量表达式:

语句;

#define _CRT_SECURE_NO_WARNINGS

#include

int main()

{

int day = 0;

scanf("%d", &day);

switch (day)//switch决定从哪里进去

{

case 1:

printf("星期一\n");

break; //berak跳出switch语句

case 2:

printf("星期二\n");

break;

case 3:

printf("星期三\n");

break;

case 4:

printf("星期四\n");

break;

}

return 0;

}

扩展

#define _CRT_SECURE_NO_WARNINGS

#include

int main()

{

int day = 0;

scanf("%d", &day);

switch (day)

{

case 1:

case 2:

case 3:

case 4:

case5:

printf("工作日\n");

break;

case6:

case7:

printf("休息日",\n);

break;

default: //在范围之外,警告错误

printf("输入错误");//

break;

}

return 0;

}

练习

#define _CRT_SECURE_NO_WARNINGS

#include

int main()

{

int n = 1;

int m = 2;

switch(n)//以n为入口,switch判断的是n的值,n是2就执行case2

{

case 1:m++;//m=3

case 2:n++;//n=2

case 3:

switch (n)//以n为入口

{

case 1:n++;//n=2,case 1不执行,因为2就是case2,如果这时n还是1,就从case1开始执行

case 2:m++;//m=4

n++;//n=3

break;

}

case 4:m++;//m=5

default:

break;

} printf("m=%d,n=%d\n", m, n); return 0;

}

结果是m=5,n=3;

循环语句

while循环

语法结构:

while(表达式)

循环语句;

表达式结果为真,语句将被执行,

为假,循环不再执行

例:

在屏幕上打印1-10

#define _CRT_SECURE_NO_WARNINGS

#include

int main()

{

int i = 1;

while (i

{

printf("%d\n", i);

i++;

}

return 0;

}

循环里break作用

#include

int main()

{

int i = 1;

while (i<=10) { if (i == 5)//i=5时停止打印,所以结果是1234 break; printf("%d\n", i); i++; } return 0;

}

循环里面的continue

#include

int main()

{

int i = 1;

while (i<=10) { if (i == 5) continue;// printf("%d\n", i); i++; } return 0;

}

结果是1234_ 程序未结束

陷入了死循环

continue作用:跳过本次循环体中余下尚未执行的语句,立刻进行下一次循环

getchar

 

#define _CRT_SECURE_NO_WARNINGS

#include

int main()

{

int ch = 0; //创建了一个整形变量

//ctrl+z,getchar获取了EOF就停下来了//EOF:end of file文件结束标志,本质上是-1,

while ((ch = getchar()) != EOF)//getchar获取字符,接受键盘输入一个字符,getchar获取一个字符放到ch里面去,

//获取的字符是不是EOF,如果不等于EOF,就把字符打印一下,

//获取EOF,这个循环也停不下来,因为只是单独的E,O,F

putchar(ch); //putchar输出,输出ch,打印在屏幕上,与printf("%c\n",ch);等价,但简洁

return 0;

}

代码1

#define _CRT_SECURE_NO_WARNINGS

#include

int main()

{

int ret = 0;

char password[20] = { 0 };

printf("请输入密码:>");

scanf("%s",password);//输入密码,并存放在password数组中,%s表示输入的是字符串

printf("请确认(Y/N):>");

ret = getchar();//Y/N

if (ret == 'Y')

{

printf("确认成功");

}

else

{ printf("放弃确认\n");// } return 0;

}

代码2

#include

int main()

{

char ch = '\0';

while ((ch = getchar()) != EOF)

{

if (ch < '0' || ch > '9')

continue;

putchar(ch);

}

return 0;

} //只打印字符0-9,其他字符不打印

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值