当前位置:网站首页>Branch and loop sentence exercises
Branch and loop sentence exercises
2022-07-28 00:56:00 【Xu Hanhan!】
For personal reasons , I haven't updated my blog for a long time , Starting today , I will continue to update for you C And later knowledge .
Then the last blog , In the last blog, we explained the knowledge points of branch and loop statements , Strike while the iron is hot , Let's update some related topics in my learning process , For everyone to study together !!!
1. Calculation n The factorial .
thought :
1. formation 1-n The number of
2. Can be simplified n The factorial
for example :2!= 1!*2 3!= 2!*3.....n! = (n-1)!*n In fact, we only need to multiply each generated number by the factorial of the previous number ( After learning functions in the later stage, you can also use the recursive method to write , Here we only use the iterative method to write )
int main()
{
int n = 0;
scanf("%d", &n);
int ret = 1;// Note that this can't be 0
// Generate 1-n The number of
int i = 0;
for (i = 1; i <= n; i++)
{
ret = ret * i;
}
printf("%d\n", ret);
return 0;
}
We type in 5 You know 5!=120.
2. Calculation 1!+2!+3!+……+10!thought :This question is only an expansion of the first question , We just need to define another sum Variable , Add the factorial calculated each time to sum You can go up.
int main()
{
int ret = 1;
int sum = 0;
// Generate 1-10 The number of
int i = 0;
for (i = 1; i <= 10; i++)
{
ret = ret * i;
sum = sum + ret;
}
printf("%d\n", sum);
return 0;
} 
Readers can set variables to verify whether the logic of the code is correct !
3. Find a specific number in an ordered array n.( Explain two-point search )thought :The main idea of this topic is binary search , That is, what is often called half search ;First we need to define a left The variable points to the first element of this ordered array , Define a right The variable points to the last element of the ordered array ( among right Variables we can use sizeof The operator of gets , namely right=sizeof(arr)/sizeof(arr[0])-1, Let me define one more mid The variable points to the middle element of this array , To prevent mid Variable out of bounds , We can make mid=left+(right-left)/2;If the element searched is more than mid The element pointed to is larger left=mid+1, If the element searched is more than mid The element pointed to is small right=mid-1, If it is equal, the search is successful , You can exclude half of the elements every time you look up , Its time complexity is logn, When left>right when , Find the end , If you haven't found , The search fails !
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };// Define an integer array
int k = 7;// If you find the element of 7
int sz = sizeof(arr) / sizeof(arr[0]);// Calculate the number of elements of an integer array
int left = 0;
int right = sz - 1;
// lookup
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] > k)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
printf(" eureka , Subscript to be :%d\n", mid);
break;// If the search is successful, it will jump out of the loop
}
}
if (left > right)
{
printf(" To find the failure \n");
}
return 0;
} 
Be careful :
1.mid Variables must be defined and then while Internal loop , Because every time I search mid Will change
2. Finding the length of an integer array will be used in the future sizeof(arr)/sizeof(arr[0])
3. To prevent mid Variable out of bounds , We usually use mid = left+(right-mid)/2 , Readers can draw pictures by themselves
4. Write code , Demonstrate the movement of multiple characters from both ends , Converging in the middle .thought :Define two arrays , Define two more variables , The first element of an array , Another one points to the last element of the array ( The same idea as the above question ), Assign an element in one array to another array at a time , Then make left++,right--, When left>right when , Indicates that the operation is complete , Exit loop#include <string.h> #include <windows.h> int main() { char arr1[] = "hello world!!!"; char arr2[] = "##############"; int sz = strlen(arr1);// Find the length of the array int left = 0; int right = sz - 1; // In exchange for while (left <= right) { system("cls");// Clear the screen arr2[left] = arr1[left]; arr2[right] = arr1[right]; left++; right--; printf("%s\n", arr2); Sleep(500);// Stop 500ms } return 0; }
Because every time printf Inside the loop , And every cycle will clear the screen , So it's a dynamic process , You can see for yourself when compiling !
Be careful :
1. There are two ways to find the length of a character array : The first is the use of the previous question sizeof solve , The second is the use written here strlen, Library functions need to be called string.h
2. there system("cls") Is the screen clearing function ,Sleep(500) In order to make the printed results stay on the screen , The time to stay is defined by yourself , In milliseconds , Library functions need to be called windows.h
5. Write code to achieve , Simulate user login scenarios , And can only log in three times .( Only three passwords are allowed , If the password is correct Prompt to log in as , If all three inputs are wrong , Then exit the program .thought :Use a loop to simulate login , Cycle three times , If the password is correct within three times break Jump out of the loop to prompt that the login is successful , Otherwise, the login fails#include <string.h> int main() { char password[20] = { 0 };// Suppose the password is abcdef printf(" Please log in \n"); int i = 0;// Record the number of logins while (i < 3) { printf(" Please input a password :"); scanf("%s", password); if (strcmp(password, "abcdef") == 0) { printf(" Login successful \n"); break; } else { printf(" Wrong password , Please re-enter \n"); i++; } } if (i == 3) { printf(" Three incorrect password entries , Exit procedure \n"); } return 0; }
Login successful :

Login failed :

Be careful :
When comparing strings for equality , need strcmp function , If equal, the result is 0, Library functions need to be called string.h
5. Guess the number game to achieve
thought :
utilize srand Function generation 1-100 The number of , Guess the numbers , Guess the logic of numbers : If the guessed number is larger than the randomly generated number, it indicates that the guess is big , If it is smaller than the randomly generated number, it will prompt you to guess smaller , Otherwise, guess success
#include <stdlib.h>
#include <time.h>
// Print the game menu interface
void menu()
{
printf("************************\n");
printf("***** Guess the number game *****\n");
printf("***** 1.play *****\n");
printf("***** 0.exit *****\n");
printf("************************\n");
}
// Print the game menu interface
void game()
{
int ret = rand() % 100 + 1;
int k = 0;
printf(" Guess the number \n");
while (1)
{
printf(" Please enter :");
scanf("%d", &k);
if (k < ret)
{
printf(" Guess a little \n");
}
else if (k > ret)
{
printf(" Guess the \n");
}
else
{
printf(" congratulations , Guessed it \n");
break;
}
}
}
int main()
{
srand((unsigned int)time(NULL));// Define the starting point of random number generation
int input = 0;
do
{
menu();// Print the game menu interface
printf(" Please select :");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf(" Quit the game \n");
break;
default:
printf(" Input error , Please re-enter \n");
break;
}
} while (input);
return 0;
}
Be careful :
srand Function is used to define the starting point of generating random numbers , The timestamp is used here , The starting point of each game time only needs to be defined once , therefore srand The function is defined at the beginning of the main function
That's all for loop and branch statements , Mastering these topics in this chapter will significantly improve your level !
come on. , Thank you Sanlian !!!
边栏推荐
- 网络设备硬核技术内幕 防火墙与安全网关篇 (十二) 零接触办公的奥秘 下
- Arm发布全新A78/G78/N78内核!还有支持自定义的Cortex-X系列CPU
- Jerry's prompt sound processing when switching devices [chapter]
- 【C语言入门】ZZULIOJ 1026-1030
- Jerry caused other messages to accumulate in the message pool [article]
- Add a picture in front of the cell
- 蓝桥杯单片机第十一届国赛程序设计试题
- Focus on demand flow rather than idle people
- Programmer growth Chapter 30: do you really understand feedback?
- 函数相关知识
猜你喜欢

立即报名 | 云原生技术交流 Meetup 广州站已开启,8 月 6 号与你相遇!

mysql数据库的基本操作(一)-——基于数据库
![Leetcode:1997. the first day after visiting all rooms [jump DP]](/img/6e/52d5871a11d1b27e673112a8245b28.png)
Leetcode:1997. the first day after visiting all rooms [jump DP]
![[proteus simulation] 51 single chip microcomputer washing machine simulation control program](/img/a1/d4256a5e350078b791c0b5cd512fe3.png)
[proteus simulation] 51 single chip microcomputer washing machine simulation control program

Confused SCM matrix keys

mysql数据库的基本操作(三)-——基于字段

小波变换学习笔记

Resolved Unicode decodeerror: 'UTF-8' codec can't decode byte 0xa1 in position 0: invalid start byte

芯片行业常用英文术语最详细总结(图文快速掌握)

SRv6初登场
随机推荐
网络设备硬核技术内幕 防火墙与安全网关篇 (五) 安全双修大法 中
基于Unittest的ddt+yaml实现数据驱动机制
The influence of head zeroing and tail zeroing on FFT output
【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发
When Jerry made a phone call, recording to SD card /u disk was not enough [article]
立即报名 | 云原生技术交流 Meetup 广州站已开启,8 月 6 号与你相遇!
Arm发布全新A78/G78/N78内核!还有支持自定义的Cortex-X系列CPU
Code review tool
Network equipment hard core technology insider firewall and security gateway (12) the mystery of zero contact office
Redis-三大特殊数据类型的学习和理解
Rendering problems
小程序助力智能家居生态平台
[meetup preview] openmldb + ONEFLOW: link feature engineering to model training to accelerate machine learning model development
【OpenCV 例程 300篇】241. 尺度不变特征变换(SIFT)
Arm releases the new a78/g78/n78 kernel! There is also a cortex-x Series CPU that supports customization
Basic operations of MySQL database (I) --- Based on Database
Network equipment hard core technology insider firewall and security gateway (11) secrets of zero contact office
leetcode:1997. 访问完所有房间的第一天【跳跃dp】
为华为打造无美系设备的产线,台积电三星能做到吗?
leetcode 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球(中等)