if语句
if(表达式)
语句;
if(表达式)
语句1;
else
语句2;
多分枝
if(表达式1)
语句1;
else if(表达式2)
语句2;
else
语句3;
如果条件成立,要执行多条语句,则应该使用代码块
int main()
{
int age = 40;
if (age < 18)
printf("未成年\n");
else if(age>=18 && age<=28)
printf("青年人\n");
else if(age >=28 && age <=50)
printf("成人\n");
return 0;
}
int main()
{
int a = 1;
//printf("1-100之间的奇数\n");
while (a <=100)
{
if (a % 2 == 1)
printf("%d ", a);
a++;
}
return 0;
}
switch语句--解决多分枝问题(后面的表达式必须为整形)
switch(表达式)
case --入口(必须为整形 常量 表达式)
break--出口
eg:1-5为工作日 6-7为休息日
int day = 0;
scanf("%\d", &day);
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("工作日\n");
break;
case 6:
case 7:
printf("星期天\n");
break;
}
return 0;
int main()
{
int day = 0;
scanf("%\d", &day);
switch (day)
{
case 1:
printf("星期一\n");
break;
case 2:
printf("星期二\n");
break;
case 3:
printf("星期三\n");
break;
case 4:
printf("星期四\n");
break;
case 5:
printf("星期五\n");
break;
case 6:
printf("星期六\n");
break;
case 7:
printf("星期天\n");
break;
default:
printf("输入错误\n");
break;
}
return 0;
}
continue--终止本次循环中continue后面的代码
int main()
{
int i = 1;
while (i <= 10)
{
if (i == 5)
continue;
printf("%d\n", i);
i++;
}
return 0;
}
int main()
{
int ch = getchar();
while((ch=getchar())!='\n')
putchar(ch);
printf("%c\n",ch)
return 0;
}
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
{
if (ch < '0' || ch>'9')
continue;
putchar(ch);
}
return 0;
}
for循环
在for循环中break也可跳出循环
continue会跳出后面的代码块 继续执行
取值采用前闭后开区间
不可在for循环体内修改循环变量,防止for循环失控
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
for循环的变种1
for循环的初始化,范围,判断都可以省略
1、判断条件省略就是恒为真
2、不熟练建议不要随便省略
int main()
{
for (;;)
{
printf("hehe\n");
}
}
变种2
int main()
{
int x ,y;
for (x = 0, y = 0; x < 2 && y < 5; ++x, y++)
{
printf("hehe\n");
}
return 0;
}
do while循环
int main()
{
int i = 1;//先创建变量
do
{
printf("%d ", i);//打印1
i++;//变成2
} while (i <= 10);//进行判断再进入到do while中
return 0;
}
int main()
{
int n=0;
int i=0;
int ret = 1;
scanf("%d", &n);
for (i = 1; i <=n; i++)
{
ret = ret * i;
}
printf("ret=%d\n", ret);
return 0;
}
int main()
{
char arr1[] = "welcome to LanZhou!!!!!!";
char arr2[] = " ";
int left = 0;
int right = strlen(arr1) - 1;
while (left <= right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n", arr2);
Sleep(1000);
system("cls");
left++;
right--;
}
printf("%s\n", arr2);
return 0;
}
int main()
{
int i = 0;
char password[20] = { 0 };
for (i = 0; i < 3; i++)
{
printf("请输入密码:>");
scanf("%s", password);
if (strcmp(password,"123456")==0)//==不能用于比较两个字符串是否相等,应该使用一个库函数-strcmp
{
printf("登录成功!!!\n");
break;
}
else
{
printf("密码错误,请重新输入\n");
}
}
if (i == 3)
{
printf("三次密码均输入错误,请按任意键退出");
}
return 0;
}
标签:case,return,int,哥学,C语言,break,第四天,printf,main From: https://blog.51cto.com/u_16021563/6163623