有关循环语句的程序小练习

计算n的阶乘

int main()
{
int i=0;
int ret=1;
scanf("%d",&i);
for(i=1;i<=n;i++)
{
ret=ret*i;
}
printf("%d\n",ret);
return 0;
}

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

int main()
{计算1!+2!+3!+.....+10!
	int i = 0;
	int j = 0;
	int sum = 0;
	int ret = 1;
	for (i = 1; i <= 3; i++)
	{
		ret = 1;
		for (j = 1; j <= i; j++)
		{
			ret = ret * j;
			
		}sum += ret;
	}
	printf("%d\n", sum);
	return 0;
}//算法效率低
//效率高的方法
int main()
{
    int n=0;
	int sum = 0;
	int ret = 1;//不可赋初值为0,0乘以任何数都为0
 for(n=1;n<=10;n++)
 {
     ret*=n;//阶乘
     sum+=ret;//求和
 }
 printf("%d\n",sum);
 reurn 0;
 }

在一个有序数组中查找具体的某个数字n

折半查找/二分查找(前提条件是数组有序)

left mid right

arr[mid]中间元素


int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int k=10;//查找k,k的值可以是数组中的任意数
	int sz = sizeof(arr) / sizeof(arr[0]);//40/4

	int left = 0;
	int right = sz - 1;//-1是因为数组下标从0开始

	while (left <= right)//不能漏掉=
	{
		int mid = left + (right-left) / 2;//中间元素必须放到循环里面
		//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;
}

编写代码,演示多个字符从两端向中间汇聚

#include
#include
#include

int main()
{
    //下标从0开始且减去\0所以得减去2
    //sizeof(arr1)/sizeof(arr[0])-2;//4
    //char arr[] = "abc";
    //[a b c \0]
    
    char arr1[] = "welcome to bit!!!!!";
    char arr2[] = "###################";
    
    int left = 0;
    //int right = sizeof(arr1)/sizeof(arr[0])-2;
    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; 
}

模拟用户登录情景

密码最多输入三次,,正确则提示输入成功,输入三次错误就退出程序

两个字符的比较不能使用==,应该使用strcmp

#include
#include

int main()
{
    int i = 0;
    char password[20] = {0};
    //假设正确密码是“abcdef”
    for(i = 0; i < 3; i++)
    {
        printf("请输入密码:");
        scanf("%s",passsword);
        if(strcmp(password,"abcdef")==0)
        {
            printf("密码正确\n");
            break;
        }
       else
       {
           printf("密码错误,重新输入\n");
       } 
    }
    if (i == 3)
	{
		printf("三次密码均错误,退出程序\n");
	}
	return 0;
}

你可能感兴趣的:(笔记,蓝桥杯,职场和发展)