分支与循环练习题
- 计算n的阶乘
int main(){
int i = 0;
int n = 0;
int sum = 1;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum = i * sum;
}
return 0;
}
- 1的阶乘+2的阶乘+…10的阶乘
int main(){
int i = 0;
int n = 0;
int sum = 1;
int ret = 0;
for(n =1;n<=10;n++)
{
sum = 1;
for(i=1;i<=n;i++)
{
sum = i * sum;
}
ret = ret +sum
}
return 0;
}
- 写一个代码,在arr数组(有序的)找到7
int main(){
int arr[] = {1,2,3,4,5,6,7,8,9,10}'
int k = 7;
int i = 0;
int sz = sizeof(arr)/sizeof(arr[0]);//元素个数
for(i=0;i<sz;i++)
{
if(k == arr[i])
{
printf("找到了,下标是:%d\n",i);
break;
}
}
if(i == sz)
printf("找不到\n");
return 0;
}
可以使用效率更高的折半查找
int arr[] = {1,2,3,4,5,6,7,8,9,10}'
int k = 7;
int sz = sizeof(arr)/sizeof(arr[0]);//得到元素个数
int left = 0;
int right = sz-1;
while(left<=right)
{
int mid = (left + right)/2;
if(arr[mid] >k)
{
right = mid -1;
}
else if(arr[mid] <k)
{
left = mid +1;
}
else
{
printf("找到了,下标是:%d\n",mid);
break;
}
}
if(left>right)
{
printf("找不到\n");
}
return 0 ;
- 从两端打印到中间
#include<stdio.h>
#include<string.h>
#include<windows.h>
#include<stdlib.h>
int main(){
char arr1[] = "welcome to my home!!!";
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);//休息1000毫秒,也就是一秒,需要引入头文件 windows.h
system("cls");//执行系统命令的一个函数 cls -清空屏幕 需要引入头文件
left ++;
right --;
}
return 0;
}
- 输入三次密码,密码均错误就退出
int main()
{
char password[20] = {0};
int i = 0;
for(i = 0;i<3;i++)
{
printf("请输入密码:");
scanf("%s",password);
if(strcmp(password,"123456") == 0)
//这里不能简单的用password == 123456,字符串的比较要用到库函数 strcmp
{
printf("登陆成功\n");
break;
}
else
{
printf("棉麻错误\n");
}
}
if(i == 3)
printf("三次密码错误,退出程序\n");
return 0;
}