当前位置:网站首页>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 !!!
边栏推荐
- 小波变换学习笔记
- Current situation of semiconductor testing equipment Market: the localization rate is still less than 10%!
- ASML launched the first generation HMI multi beam detector: the speed is increased by 600%, which is suitable for 5nm and more advanced processes
- map集合
- Buildforge materials
- 阿里二面:为什么要分库分表?
- MySQL中的运算符
- mysql数据库的基本操作(二)-——基于数据表
- 融云 IM & RTC 能力上新盘点
- 芯片行业常用英文术语最详细总结(图文快速掌握)
猜你喜欢

"C language" deep entry rounding & four functions

110. SAP UI5 FileUploader 控件深入介绍 - 为什么需要一个隐藏的 iframe

How does JMeter solve the problem of garbled code?

数据分析:拆解方法(详情整理)
![Jerry Zhi doesn't play hidden audio files [article]](/img/09/b9fb293151f56d2a93f8a1c8f3d0dc.png)
Jerry Zhi doesn't play hidden audio files [article]

小波变换学习笔记
![[CruiseControl]Build Result JSP](/img/80/11c2b539c217ecd6ba55668d3e71e9.png)
[CruiseControl]Build Result JSP

What is the org relationship mitigation strategy of Microsoft edge browser tracking prevention

福特SUV版“野马”正式下线,安全、舒适一个不落

Syntaxerror resolved: positive argument follows keyword argument
随机推荐
程序员成长第三十篇:你真的懂反馈吗?
进程与进程调度
一文读懂CMake
迷惑的单片机矩阵按键
小程序助力智能家居生态平台
Logic of automatic reasoning 09 - automatic theorem proving
LSB steganography
Volkswagen China invested 8billion yuan and became the largest shareholder of GuoXuan high tech
[CruiseControl]Build Result JSP
网络设备硬核技术内幕 防火墙与安全网关篇 (十二) 零接触办公的奥秘 下
KMP review + AC automata Prequel
Map set
R language evaluates the relative importance of the predictive factors (variables, characteristics) of the regression model, scales the predictive variables of the regression model, and then construct
Arm releases the new a78/g78/n78 kernel! There is also a cortex-x Series CPU that supports customization
Network device hard core technology insider firewall and security gateway (IX) virtualization artifact (II)
融云 IM & RTC 能力上新盘点
Valued at $36billion! SpaceX, which is about to launch its first manned launch, raised $346million
蓝桥杯单片机第十一届国赛程序设计试题
为华为打造无美系设备的产线,台积电三星能做到吗?
[proteus simulation] 51 single chip microcomputer washing machine simulation control program