# while循环

``````//while 语法结构
while(表达式)
循环语句;
``````

## while语句中的break和continue

continue跳过本次后面代码，回到while的表达式判断，仅终止本次循环后面的内容。

# for循环

``````// for语法结构
for(表达式1;表达式2;表达式3)
循环语句;``````

## for语句的循环控制变量

1. 不可在for 循环体内修改循环变量，防止 for 循环失去控制
2. 建议for语句的循环控制变量的取值采用“前闭后开区间”写法

# do while循环

``````// do while循环结构
do
循环语句；
while(表达式);``````

# 题目练习

## 1.计算n的阶乘

``````# include
int main()
{
int n = 0;
printf("请输入要阶乘的数\n");
scanf("%d", &n);
int i = 0;
int ret = 1;
for (i = 1; i <= n; i++)
{
ret = ret * i;
}
printf("阶乘的值为%d\n", ret);
return 0;
}``````

## 2.计算1!+2!+3!+…+10!

``````#include
int main()
{
int n = 0;
printf("请输入要阶乘累加的数\n");
scanf("%d", &n);
int i = 0;
int ret = 1;
int sum = 0;
for (i = 1; i <= n; i++)
{
ret = ret * i;
sum = sum + ret;
}
printf("阶乘的累加值为%d\n", sum);
return 0;
}``````

## 3.在一个有序数组中查找具体的某个数字n（二分查找）

``````# include
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);	//计算数组的数量
int left = 0;
int right = sz - 1;

int k = 7;	//找下标为7所在的位置
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
printf("找到了，下标是：%d\n", mid);
break;
}
}
if (left > right)
{
printf("没找到\n");
}
return 0;
}``````

## 4.演示多个字符从两端移动，向中间汇聚

``````# include
# include
# include
int main()
{
char arr1[] = "hello world!!!";		//[h e l l ...! ! ! \0 ]
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--;
}
return 0;
}``````