评论

收藏

[C++] 五个C语言循环语句实例

编程语言 编程语言 发布于:2021-08-03 10:20 | 阅读数:389 | 评论:0

DSC0000.png
//练习1:计算n的阶乘
//while循环
int main()
{
int n;
int fact = 1;
int i = 1;
scanf("%d", &n);
while (i <= n)
 {
    fact *= i;
    i++;
  }
  printf("%d!=%d\n", n, fact);
return 0;
}
//for循环
int main()
{int n;
int fact = 1;
int i = 1;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact *= i;
  }
  printf("%d!=%d\n",n,fact);
return 0;
}
//练习2:计算1!+2!+...+10!
//while循环
int main()
{
int n;
int fact = 1;
int i = 1;
int sum = 0;
scanf("%d", &n);
while (i <= n) {
    fact *= i;
    i++;
    sum += fact;
  }
printf("sum = %d\n", sum);
return 0;
}
//for循环
int main()
{int n;
int i = 1;
int fact = 1;
int sum = 0;
scanf("%d",&n);
for(i=1;i<=n;i++){
fact *= i;
    sum += fact;
  }
printf("sum = %d\n", sum);
return 0;
}
//练习3 :在一个有序数组中查找具体的某个数字n。编写int binsearch(int x,int v[],int n);
//功能:在v[0] <= v[1] <= v[2] ... <= v[n-1] 的数组中查找x。
//递归算法
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int k = 7;
//写一个代码在数组里找到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 main()
{int arr[] = {1,2,3,4,5,6,7,8,9,10};
int left = 0;//左下标
int right = sz - 1;//右下标
while(left<=right)
{
int mid = (left + right)/2;
    if(arr[mid] &gt; k)
    {
      right = mid-1;
    }
    else if(arr[mid] &lt; k)
    {
      left = mid-1;
    }
    else
    {
      printf("找到了,下标是:%d\n",mid);
      break;
    }
  }
  if(left&gt;right)
  {
    printf("找不到\n");
  }
return 0 ;
}
//练习4 : 编写代码,演示多个字符从两端移动,向中间汇聚include <stdio.h>include <string.h>include <windows.h>include <stdlib.h>
int main()
{
char arr1[] = "welcome to bit!!!!!!";
char arr2[] = "####################";
int left = 0;
//int right = sizeof(arr1)/sizeof(arr1[0])-2;//字符串最后一个隐形的\n
int right = strlen(arr1)-1;
while(left<=right)
 {
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n",arr2);
Sleep(1000);
system("cls");//执行系统命令的一个函数-cls-清屏
left++;
right--;
}
return 0 ;
}
//练习5 : 编写代码实现,模拟用户登录情景,并且只能登录三次。(只允许输入三次密码, 如果密码正确则提示登录成功,如果三次均错误,则退出程序。)
int main()
{
int i = 0 ;
char password[20] = {0};
for(i=0;i<3;i++)
 {
    printf("请输入密码:&gt; ");
    scanf("%s",password);
    //if(password == "123456")
    //== 不能用来比较两个字符是否相等,应该使用一个库函数-strcmp
    if(strcmp(password,"123456") == 0)
    {
      printf("登陆成功\n");
      break;
    }
    else
    {
      printf("密码错误。\n");
    }
  }
  if(i == 3)
  {
    printf("三次密码均错误,退出程序。\n");
  }
return 0 ;
}
关注下面的标签,发现更多相似文章