语句
if...else
c
#include <stdio.h>
int main(void)
{
int a = 60;
float b = 70.5;
if (a > 60)
{
printf("大于 60");
}
else if (a < b)
{
printf("a 小于 b");
}
else
{
printf("小于 60");
}
}
三目运算符
c
#include <stdio.h>
int main(void)
{
int a = 60;
float b = 70.5;
printf(a > 60 ? ("大于 60") : "a 小于 b");
}
switch
c
#include <stdio.h>
int main(void)
{
char c;
c = getchar();
switch (c) // 参数只能是整型变量
{
case '1':
printf("OK\n");
break; // switch遇到break就中断了
case '2':
printf("not OK\n");
break;
default: // 如果上面的条件都不满足,那么执行default
printf("are u ok?\n");
}
}
while
c
#include <stdio.h>
int main()
{
int a = 20;
while (a > 10)
{
scanf("%d", &a);
printf("a = %d\n", a);
}
return 0;
}
do while
c
#include <stdio.h>
int main()
{
int a = 1;
do
{
a++;
printf("a = %d\n", a);
} while (a < 10);
return 0;
}
for
c
#include <stdio.h>
int main()
{
int i;
int sum = 0;
for (i = 0; i <= 100; i++)
{
sum += i;
}
printf("sum = %d\n", sum);
return 0;
}
跳转语句
break
c
#include <stdio.h>
int main()
{
int i = 0;
while (1)
{
i++;
printf("i = %d\n", i);
if (i == 10)
{
break; //跳出while循环
}
}
int flag = 0;
int m = 0;
int n = 0;
for (m = 0; m < 10; m++)
{
for (n = 0; n < 10; n++)
{
if (n == 5)
{
flag = 1;
break; //跳出for (n = 0; n < 10; n++)
}
}
if (flag == 1)
{
break; //跳出for (m = 0; m < 10; m++)
}
}
return 0;
}
continue
c
#include<stdio.h>
int main()
{
int sum = 0; //定义变量sum
for (int i = 1; i <= 100; i++)
{
if (i % 2 == 0) //如果i是一个偶数,执行if语句中的代码
{
continue; //结束本次循环
}
sum += i; //实现sum和i的累加
}
printf("sum = %d\n", sum);
return 0;
}
goto
无条件跳转,尽量少用
c
#include <stdio.h>
int main()
{
goto End; //无条件跳转到End的标识
printf("aaaaaaaaa\n");
End:
printf("bbbbbbbb\n");
return 0;
}