当前位置:网站首页>Section 3 - functions
Section 3 - functions
2022-06-13 04:47:00 【Stretch the curtain with the wind】
Catalog
2.c Classification of functions in language
2.1.1. How to learn to find library functions
2.1.2. Some library function demonstrations ( Reference document , Learn several library functions )
2.2.1. Custom function introduction
2.2.2. Function application examples (※)
3. The parameters of the function
3.1. The actual parameter ( Actual parameters )
3.2. Formal parameters ( Shape parameter )
5. Nested calls and chained access to functions
6. Function declaration and definition
6.1. Function declaration and definition
6.2. Function code written in actual project
7.2. Two necessary conditions for recursion ( practice )(※)
7.3. Recursion and iteration ( practice )(※)
8. Several classic topics of function recursion ( Independent research )(※)
1. What is a function
We often see the concept of function in Mathematics . But you know C Functions in language ?Wikipedia definition of function : SubroutinesIn computer science , Subroutines ( English :Subroutine, procedure, function, routine, method,subprogram, callable unit), It's a piece of code in a large program , A group of one or more statement blocks become . It's responsible for a particular task , And compared to other code , With relative independence .Generally, there will be input parameters and return values , Provide encapsulation of the process and hiding of details . These codes are usually integrated into software Parts library .
2.c Classification of functions in language
1. Library function2. Custom function
2.1. Library function
2.1.1. How to learn to find library functions
Why are there library functions ?1. We know that in our study C In language programming , Always can't wait to know the result after a code is written , I want to print this result on our screen to see . At this time, we will frequently use a function : Print the information to the screen in a certain format (printf).2. In the process of programming, we will frequently copy some strings (strcpy).3. In programming, we also calculate , Always calculate n Of k Such an operation to the power (pow).Like the basic functions we described above , They are not business code . In our development process, every programmer may use , In order to support portability and improve program efficiency , therefore C A series of similar library functions are provided in the basic library of the language , It is convenient for programmers to develop software .


A brief summary ,C The library functions commonly used in the language are :IO functionString manipulation functionsCharacter manipulation functionsMemory manipulation functionTime / Date functionMathematical functionsOther library functions
2.1.2. Some library function demonstrations ( Reference document , Learn several library functions )
1.strlen function
The introduction on the website :


Code example :

Code example :
notes :memst Medium arr It's an array name , Address representing the first element of the array .
2.2. Custom function
2.2.1. Custom function introduction
If library functions can do everything , What do programmers do ?So more importantly Custom function .Custom functions are the same as library functions , Yes Function name , return type and Function parameter .But the difference is that these are all designed by ourselves . This gives programmers a lot of room to play .
Basic composition :
ret_type fun_name(para1, * ){statement;// Statement item}ret_type Return typefun_name Function namepara1 Function parameternotes :1. Functions can have no parameters and return values , If you don't need a return value , The return type is void Instead of .2. Function design should pursue high cohesion and low coupling ( Do your own thing , Try not to have anything to do with other functions )3. It's not easy to have too many function parameters .4. When designing functions , Try to release resources by those who apply ( Later on )
2.2.2. Function application examples (※)
1. Write a function to find the maximum value of two integers .
Code :

2. Write a function to exchange the contents of two shaping variables .
Error code :
Debugging of error code :
Correct code :( With the help of a pointer )
notes :
1. From here we can see that , When executing a function , The system will recreate the address for the formal parameter ( Instead of the actual parameter address when calling the function ), The system just assigns the actual parameter value in the function call to the corresponding formal parameter . In the above error code, only x and y The values of the two formal parameters are exchanged , Because it's not the same address , So it doesn't matter a and b Value .
In a nutshell : When the function is called , The actual parameter is passed to the formal parameter , A formal parameter is actually a temporary copy of an argument , Therefore, the modification of formal parameters will not affect the arguments .
3. The parameters of the function
3.1. The actual parameter ( Actual parameters )
The parameters that are actually passed to the function , It's called the actual parameter .The argument can be : Constant 、 Variable 、 expression 、 function etc. .Whatever the type of argument is , When you make a function call , They all have to have certain values , In order to pass these values to the parameter .
3.2. Formal parameters ( Shape parameter )
Formal parameters refer to the variables in brackets after the function name , Because formal parameters are only instantiated when the function is called ( Allocate memory units ), So it's called formal parameter .Formal parameters are automatically destroyed when the function call is completed . So formal parameters are only valid in functions .
4. Function call
4.1. Value transfer call
The formal and actual parameters of a function occupy different memory blocks , Modification of a parameter does not affect the argument .
4.2. Address call
Address call is a way to call a function by passing the memory address of the created variable outside the function to the function parameter .This parameter transfer method can establish a real relationship between the function and the variables outside the function , That is, you can directly operate inside the functionAs a variable outside the function .
notes :
1. Because the address of the first element of the array is actually passed when transmitting the array , Therefore, when using an array to pass, it is equivalent to an address call .
2. The function of address transfer can be realized by using global variables , But not recommended .
4.3. practice (※)
1. Write a function to determine whether a number is a prime .2. Write a function to determine whether a year is a leap year .3. Write a function , To realize binary search of an ordered array .4. Write a function , Every time you call this function , Will be num The value of the increase 1.5. With the help of functions : If certain conditions are met (n=5) Output hehe, Otherwise output haha.

Exercises 2:
Exercises 3:
Error code :
Error code run result :
Correct code :
Correct code run results :
notes : Array arr Pass to binary_search When , In fact, the message is arr Address of the first element of the array , When passing parameters to an array like this , The number of such elements must be calculated outside and then passed in .
Exercises 4:
Correct code 1:
Correct code 2:
Correct code 3:
Error code :
Exercises 5:
notes : Function , If you want the function to end early , By means of return Realization , Code above , Functions with return values use return Add the return value to realize , Having no return value , Just one return And then .
5. Nested calls and chained access to functions
5.1. Nested calls

notes :
1. The calling relationship is :main Function call three_line,three_line It calls new_line. Functions can be called to each other , Nested call .
2. Functions can be called nested , But you can't nest definitions . Here's the picture Is an example of a nested definition , It's wrong. . All functions must be at the same level .
5.2 Chained access
Take the return value of one function as the parameter of another function .

Knowledge point 2:
Code :

Running results :
notes : Here's the picture MSDN Yes printf Function introduction ,printf The return value of the function is the number of characters that the function prints on the screen ( If an error occurs during printing , Return a negative number )

6. Function declaration and definition
6.1. Function declaration and definition
Function declaration :1. Tell the compiler that there is a function called , What are the parameters , What is the return type . But does it exist , Function declarations do not determine .2. The declaration of a function usually precedes the use of the function . To satisfy the requirement of declaration before use .3. The declaration of the function is usually placed in the header file .Function definition :The definition of a function refers to the concrete implementation of a function , Explain the function realization .
Functions are defined directly before the function is used :


6.2. Function code written in actual project



The process : A company doesn't write add The code needs to be written by a programmer , So programmers need to write add.c Document and add.h File and then encrypt the static library of the project where the two files are located ( The binary ), then add.h The header file ( The header file is equivalent to the specification , Let the company know what the function parameters are , Know how to use this function ) And static library encryption add.lib Documents are sold to the company ( Can't sell add.c file , If you sell add.c file , Companies know the function implementation code , Programmers can't sell to other companies ), Company import add.h Documents and declarations add.lib File with its own main function code can be achieved .
1. The code the programmer has to write :


3. take .h and .lib Documents are sold to the company

7. Function recursion
7.1. What is recursion
The programming skill of program calling itself is called recursion ( recursion), Function calling itself is function recursion .Recursion as an algorithm is widely used in programming languages . A procedure or function has the function of directly or indirectly calling itself in its definition or description A method for the , It usually transforms a large and complex problem into a smaller problem similar to the original problem to solve .The recursion strategy only needs a few programs to describe the repeated calculation needed in the process of solving problems , Greatly reduces the amount of code in the program .The main way to think about recursion is : Turn the big thing into a small one
Simple recursive code ( It's recursive code , But it will die ):
Running results : Dead cycle ( The program in the figure crashed , So stop )
Error reporting of procedures :
notes :stack overflow Stack overflow means stack overflow , Very common errors in recursive code .
7.2. Two necessary conditions for recursion ( practice )(※)
1. There are restrictions , When this constraint is met , Recursion doesn't continue .2. After each recursive call, it gets closer and closer to this constraint .notes : If the condition is not met, it will recurse wirelessly , Stack overflow occurs .
Exercise one :
Receive an integer value ( Unsigned ), Print each bit of it in order .for example :Input :1234 Output :1 2 3 4
Code :

notes :
1.%u Stands for unsigned integer .
2. If there is no if Statement restrictions , It will be the same as the one in front main equally , Infinite recursion , Last appearance Stack overflow (stackoverflow) The phenomenon of , Cause the program to crash .( There is a foreign website called stackoverflow Equivalent to the programmer's knowledge , If you don't know, you can ask questions on it )Stack Overflow - Where Developers Learn, Share, & Build Careers
Stack overflow : Each function call will request a space in the stack area of memory , If wireless recursion goes on , Stack space will be used up , No space can be opened up , There will be stack overflow .

Exercise 2 :
Writing functions does not allow the creation of temporary variables , Find the length of the string .( It means to write a function to realize the function strlen Function functions )
Code 1:( In fact, this code creates count Temporary variable , Does not meet the requirements of the topic )
Code 2: ( The code that conforms to the meaning of the question )
Code 2 Graphic interpretation :
7.3. Recursion and iteration ( practice )(※)
seek n The factorial .( Don't think about spillovers )

Recursively implemented code :

Please n Fibonacci Numbers .( Don't think about spillovers )Fibonacci number :1 1 2 3 5 8 13 21 34 55......




notes : Here the recursive system repeats many calculations , Efficiency is very low , For example, below , Computation first 40 individual Fibonacci number of hours , The third Fibonacci number is calculated 39088169 Time .
8. Several classic topics of function recursion ( Independent research )(※)
1. The hanotta problem2. The problem of frog jumping on the steps
8.1. The hanotta problem
subject :It's said that in the ancient temple of India , There is one called the Hanoi Tower (Hanoi) The game of . The game is on a copper device , There are three rods ( Number A、B、C), stay A From the bottom up 、 Place in order from large to small 64 A gold plate ( Pictured 1). The goal of the game : hold A All the gold plates on the pole are moved to C On the pole , And still keep the original order . Operating rules : Only one plate can be moved at a time , And keep the big plate down all the time during the moving process , Small in , The plate can be placed during the operation A、B、C On any pole .
Code :
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void move(char pos1, char pos2)
{
printf("%c->%c ", pos1, pos2);
}
void Hanoi(int n, char pos1, char pos2, char pos3)
{
if (n == 1)
{
move(pos1, pos3);
}
else
{
Hanoi(n - 1, pos1, pos3, pos2);
move(pos1, pos3);
Hanoi(n - 1, pos2, pos1, pos3);
}
}
int main()
{
int n = 0;
printf(" Please enter the number of plates :");
scanf("%d", & n);
Hanoi(n, 'A', 'B', 'C');
return 0;
}
Running results :
analysis :
From this question we can see , In the case of the tower of Hanoi :A The rod is the starting rod ,B The rod is a transfer rod ,C The pole is the target pole .

8.2. The problem of frog jumping on the steps
subject :A frog can jump up at a time 1 Stepped steps , You can jump on it 2 level . Ask the frog to jump on one n How many jumps are there in the steps ?( Different results are calculated according to different order ).
Code :
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int fib(int n)
{
if (n == 1)
return 1;
else if (n == 2)
return 2;
else
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n = 0;
printf(" Please enter the order :");
scanf("%d", &n);
int s = fib(n);
printf(" All in all %d Jump \n", s);
return 0;
}
Running results :
analysis :
To put it another way , It's a number n, Let go 1 and 2 Formed by different arrangements . Due to the influence of arrangement order , For slightly larger n Come on , There are many kinds .
n=1, Only One Jump ,[1].
n=2, So there are two Jump ,[2],[1,1].
n=3, So there are 3、 ... and Jump ,[1,1,1],[1,2],[2,1].
n=4, So there are 5、 ... and Jump ,[1,1,1,1],[1,1,2],[1,2,1],[2,1,1],[2,2].
n=5, So there are 8、 ... and Jump ,[1,1,1,1,1],[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1],[2,2,1],[2,1,2],[1,2,2].
We found that , When n Add... In turn 1 when , Its combinatorial number just constitutes a Fibonacci sequence ( That is, the size of a certain number , Equal to the sum of the two preceding numbers ).
Depth analysis :
hypothesis n A stair , Yes f(n) Seed walking method . Frogs can jump for the first time 1 A step or 2 A stair , If you jump one step, you'll be left with n-1 There are steps f(n-1) Seed walking method , jump 2 One step left n-2 There are steps f(n-2) Seed walking method .
Introduction : go n There are... Steps in total f(n-1)+f(n-2) Seed walking method .
Add :
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int fib(int n)
{
if (n == 1)
return 1;
else if (n == 2)
return 2;
else if (n == 3)
return 4;
else
return fib(n - 1) + fib(n - 2) + fib(n - 3);
}
int main()
{
int n = 0;
printf(" Please enter the order :");
scanf("%d", &n);
int s = fib(n);
printf(" All in all %d Jump \n", s);
return 0;
}
边栏推荐
- LeetCode第297场周赛(20220612)
- Promise processing JS multithreads get the same processing result after all the results are obtained
- Li Kou brush question 338 Bit count
- PowerShell plus domain add computer module
- How to understand JS expressions and JS statements
- SQL notes
- Develop go using vscode
- 2022道路运输企业安全生产管理人员操作证考试题库及答案
- 如何只用4步,实现一个自定义JDBC驱动?
- Third party comment plugin
猜你喜欢
How to lay copper in AD (aluminum designer)
CreateAnonymousThreadX给匿名线程传递参数
用navicat将mysql数据转化为postgresql
PowerShell plus domain add computer module
[JS solution] leedcode 200 Number of islands
Embedded hardware - read schematic
自动评教脚本使用的配置
Collection of wrong questions in soft test -- morning questions in the first half of 2010
Cesium:cesiumlab makes image slices and loads slices
josephus problem
随机推荐
[leetcode]- sliding window
CMB's written test -- data analysis
Colab使用教程(超级详细版)及Colab Pro/Pro+评测
Your one-on-one meetings are inefficient. You can do this!
小C的记事本
E - Lucky Numbers
How to implement a custom jdbc driver in only four steps?
What is the difference between ROM, ram and flash? SRAM、DRAM、PROM、EPROM、EEPROM
约瑟夫问题
Cesium:cesiumlab makes image slices and loads slices
Implementation of article list function on PHP 18 home page
Handwritten promise and its method, with detailed notes
2022 ICLR | CONTRASTIVE LEARNING OF IMAGE- AND STRUCTURE BASED REPRESENTATIONS IN DRUG DISCOVERY
Serial communication learning
CTFSHOW 常用姿势篇(821-830)
Set properties \ classes
Several methods of identifying equivalent circuit of circuit drawing
2022年氧化工艺操作证考试题库及模拟考试
一致性哈希的简单认识
Ctfshow SQL injection (231-253)