这篇文章主要介绍“C语言分支与循环实例代码分析”,在日常操作中,相信很多人在C语言分支与循环实例代码分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C语言分支与循环实例代码分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
if语句
#include <stdio.h>
// 什么是语句?
// C语言中由一个分号;隔开的就是一条语句
; // 空语句
// 分支语句(选择结构)
int main(int argc, char *argv[])
{
int age;
printf("input your age:\n");
scanf("%d", &age);
if (age < 18)
printf("You are underage.\n");
if (age < 18)
{
printf("You are underage.\n");
printf("You can't fall in love.\n");
}
else if (age >= 18 && age < 28)
printf("You are youth.\n");
else if (age >= 28 && age < 50)
printf("You are in your prime.\n");
else if (age >= 50 && age < 70)
printf("You are elderly.\n");
else
printf("You are old.\n");
// 悬空else问题:else和离它最近的未匹配的if匹配,和缩进无关
// 判断变量与常量是否相等时把常量放在左边 5 == num ,避免num = 5的bug产生
return 0;
}
switch语句
#include <stdio.h>
int main(int argc, char *argv[])
{
int day;
printf("input a number(1-7): ");
scanf("%d", &day);
switch (day) // switch后必须是整型表达式!
{
case 1: // case后必须是整型常量表达式!
printf("Monday\n");
break; // 搭配break语句实现分支
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default: // default不一定要写在最后
printf("%d is illegal number\n", day);
break;
}
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("working day\n");
break;
case 6:
case 7:
printf("rest day\n");
break;
default:
printf("%d is illegal number\n", day);
break;
}
return 0;
}
while循环
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 1;
while (i < 11)
{
printf("%d ", i);
++i;
}
printf("\n");
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[])
{
int ch = 0;
// 输入Ctrl+z代表EOF
// EOF(end of file),值是-1
while ((ch = getchar()) != EOF)
{
putchar(ch);
}
return 0;
}
到此,关于“C语言分支与循环实例代码分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!