do while ()循环
do
循环语句;
while(表达式);
句式结构:
执行过程:
do while循环的特点:
代码练习:
二分法算法:
int main()
{
int arr[] = { 0,1,2,3,4,5,6,7,8,9};
int k = 7;//查找数字7,在arr这个数组中查找k(7)的值
int n=sizeof(arr) / sizeof(arr[0]);//数组总大小/数组单个元素的大小=数组的元素数量
int left = 0;
int right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;//数组元素中间值arr[4]
if (arr[mid] < k)
{
left = mid + 1;//范围舍去左边一半,从arr[5]开始
}
else if (arr[mid] > k)
{
right = mid - 1;//范围舍去右半边,到arr[3]结束
}
else
{
printf("找到了,下标是%d", mid);
break;
}
}
if (left > right)
{
printf("找不到\n");
}
return 0;
}
#include <string.h>
#include <windows.h>
int main()
{
char arr1[] = { "I love mum and dad" };
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);//睡眠1秒
system("cls");//清空屏幕
left++;
right--;
}
printf("%s\n", arr2);
return 0;
}
#include <string.h>
int main()
{
int i = 0;
//假设正确的密码是字符串“123456”
char password[20] = { 0 };
for (i = 0; i < 3; i++)
{
printf("请输入密码:>");
scanf("%s", password);//因为password是数组名,数组名就是地址,so无需取地址
//if (password == "123456")//err-两个字符比较,不能使用==,应该使用strcmp
if (strcmp(password, "123456") == 0)//strcmp比较的是每一位的ASCII值
{
printf("登录成功\n");
break;
}
else
printf("密码错误,重新输入\n");
}
if (i == 3)
printf("三次密码均错误,退出程序\n");
return 0;
}