当前位置:网站首页>(important) first knowledge of C language -- function
(important) first knowledge of C language -- function
2022-07-28 23:01:00 【 child】
1. What is a function
C Classification of functions in language : Library function 、 Custom function
2. Library function
2.1 strcpy
#include <stdio.h>
#include <string.h>
int main()
{
char arr1[] = "bit";
char arr2[] = "***********";
strcpy(arr2, arr1); // hold arr1 Copy the contents of to arr2 in
printf("%s\n", arr2);
return 0;
}Output results :bit
2.2 memset
#include <stdio.h>
#include <string.h>
int main()
{
char arr[] = "hello world";
memset(arr, '*', 5); // Put it in the array , front 5 Characters set to *
printf("%s\n", arr);
return 0;
}Output results :***** world
3. Custom function
(1) Compare the size of two numbers
#include <stdio.h>
int getmax(int x, int y)
{
if (x > y)
return x;
else
return y;
}
int main()
{
int a = 10;
int b = 8;
int max = getmax(a, b);
printf("%d\n", max);
return max;
}(2) Write a function that can exchange the contents of two integer variables
#include <stdio.h>
#include <string.h>
void swap1(int x, int y)
{
int temp = 0;
temp = x;
x = y;
y = temp;
}
void swap2(int *pa, int *pb)
{
int tmp = 0;
tmp = *pa;
*pa = *pb;
*pb = tmp;
}
int main()
{
int a = 10;
int b = 20;
printf("a=%d b=%d\n", a, b);
// swap1(a, b); // This method cannot
// because a,b and x,y The addresses in memory are different ,x,y The values of will be interchanged ,a,b The values of are not interchangeable
swap2(&a, &b); // Delivery address
printf("a=%d b=%d\n", a, b);
}4. Function parameter
- Actual parameters : The parameters actually passed to the function are called arguments , But constant 、 Variable 、 Expression etc. . No matter what type of variable the argument is , When you make a function call , They all have to have certain values , With These values are passed to the formal parameters .
- Shape parameter : Receive arguments , Formal parameters are variables in parentheses after the user-defined 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 . Formal parameters are formal parameters , There is no actual variable space , It will only be instantiated when called , Destroy after calling .
5. Function call
- Value transfer call : The formal and actual parameters of the function occupy different memory blocks respectively , Modification of a parameter does not affect the argument .
- Address call : A method of calling a function by passing the memory address of a variable created outside the function to a function parameter . This way of transferring parameters can make the variables outside the function establish a real connection , In other words, the variables outside the function can be directly manipulated inside the function .
- Writing rules : First write how to use in the calling function , Then write how to implement the function .
practice 1: Write a function to judge whether a number is a prime number .
#include <stdio.h>
// Function definition
int is_prime(int n){
int j = 0;
for(j=2;j<n;j++){
if(n%j == 0)
return 0;
}
return 1; // j=n
}
int main()
{
int i = 0;
for(i = 100;i<=200;i++)
{
if(is_prime(i) == 1)
printf("%d\t",i);
}
return 0;
}practice 2: Write a function to determine whether a year is a leap year .
#include <stdio.h>
// Function definition
int is_leap_year(int y){
if((y%4==0&&y%100!=0)||(y%400==0))
return 1;
}
int main()
{
int year = 0;
for(year = 1000;year<=2000;year++)
{
// Judge year Leap year or not
if(1==is_leap_year(year))
printf("%d\t",year);
}
return 0;
}practice 3: Write a function , To realize binary search of an ordered array .
// Pay attention to the array parameters , Only the address of the first original element is passed
// The number of array elements must be passed
#include <stdio.h>
// Two points search
// Find a specific number in an ordered array
// If you find the subscript of the return number , No return found -1
// Essentially arr Received pointer
int binary_search(int arr[],int k,int sz){
int left = 0;
int right = sz - 1;
while(left<=right)
{
int mid = (left+right)/2;
if(arr[mid]<k)
left = mid + 1;
else if(arr[mid]>k)
right = mid - 1;
else
return mid;
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int k = 7;
int sz = sizeof(arr)/sizeof(int);
int ret = binary_search(arr,k,sz);
// Pay attention to the array parameters , Only the address of the first original element is passed
// The number of array elements must be passed
if(ret == -1)
printf(" The specified array cannot be found \n");
else
printf(" eureka , The subscript is :%d\n",ret);
return 0;
}practice 4: Write a function , Every time you call this function , Will be num The value of the add 1
#include <stdio.h>
void Add(int *p){
(*p)++;
}
int main()
{
int num = 0;
Add(&num);
printf("num = %d\n",num); //1
Add(&num);
printf("num = %d\n",num); //2
Add(&num);
printf("num = %d\n",num); //3
return 0;
}6. Nested calls and chained access to functions
6.1 Function nested call
Each defined function can call each other
6.2 Chained access
Take the return value of one function as the parameter of another function .
7. Function declaration and definition
- Tell the compiler that there is a function called , What are the parameters , What is the return type . But does it exist , Be of no great importance .
- The declaration of a function usually precedes the use of the function , To satisfy the requirement of declaration before use .
- The declaration of a function is usually placed in the header file .
usage :
Write... In the source file .c file , Write... In the header file .h file
#ifndef LED_H // Be careful to capitalize , Quoted ****.h Lowercase
#define LED_H
*
*
*
*
#endifUse the function written by yourself "***.h", Reference downloaded or self-contained library functions to use <***.h>
8. Function recursion
- The programming technique of function calls is called recursion (recursion), Call the program yourself . Recursion as an algorithm is widely used in programming languages . A procedure or function has a method that directly or indirectly calls itself in its definition or description , 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 .
- Two necessary conditions for recursion :
- There are restrictions , When this constraint is met , Recursion doesn't continue . Prevent stack overflow ( Common mistakes in recursion ,stack overflow),
- After each recursive call, it gets closer and closer to this constraint .
practice 1: Receive an integer value ( Unsigned ), Print each bit of it in order . For example, the input 1234, Output 1 2 3 4
#include <stdio.h>
void print(int n)
{
if (n > 9)
{
print(n / 10);
}
printf("%d ", n % 10);
}
int main()
{
unsigned int num = 0;
scanf("%d", &num);
// recursive
print(num);
return 0;
}practice 2: Writing functions does not allow the creation of temporary variables , Find the length of the string
#include <stdio.h>
#include <string.h>
int my_strlen(char *str)
{
int count = 0;
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char arr[] = "hello";
int len = my_strlen(arr); // arr It's an array , Array parameters , It's not the entire array , It's the address of the first element
printf("%d\n", len);
return 0;
}边栏推荐
- HP ProLiant DL380 boot from USB flash drive, press which key
- es个人整理的相关面试题
- ValueError: Using a target size (torch.Size([64])) that is different to the input size (torch.Size([
- Stm32subeide (10) -- ADC scans multiple channels in DMA mode
- Record a question about the order of trigonometric function exchange integrals
- Cglib create proxy
- DirectX修复工具下载(exagear模拟器数据包在哪里)
- CS flow [abnormal detection: normalizing flow]
- 2020年国内十大IC设计企业曝光!这五大产业挑战仍有待突破!
- Anaconda environment installation skimage package
猜你喜欢

DIP-VBTV: Color Image Restoration Model Combining Deep Image Prior and Vector Bundle Total Variation
![[3D target detection] 3dssd (I)](/img/84/bcd3fe0ba811ea79248a5f50b15429.png)
[3D target detection] 3dssd (I)

PCA学习

TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor. cpu() to copy the tensor to

Paper reading: deep forest / deep forest /gcforest

Submission records of frontiers Publishing House (with status changes)

console.log()控制台显示...解决办法

Stm32+ four pin OLED screen + Chinese character mold taking

frontiers出版社投稿记录(附状态变化)

Nacos配置热更新的4种方式、读取项目配置文件的多种方式,@value,@RefreshScope,@NacosConfigurationProperties
随机推荐
Reading of "robust and communication efficient federated learning from non-i.i.d. data"
CGLIb 创建代理
This year, MediaTek 5g chip shipments are expected to reach 50million sets!
Submission records of frontiers Publishing House (with status changes)
轮子七:TCP客户端
Anaconda environment installation skimage package
Wheel 6: qserialport serial port data transceiver
《结构学》介绍
Anomaly detection summary: intensity_ based/Normalizing Flow
MKD [anomaly detection: knowledge disruption]
《Robust and Communication-Efficient Federated Learning From Non-i.i.d. Data》论文阅读
Target detection notes - overview and common data sets
Fastflow [abnormal detection: normalizing flow]
Learning experience sharing 5: yolov5 dataset division and Yolo format conversion
es学习目录
无代码开发平台管理后台入门教程
Xinhuazhang announced the completion of more than 200million a-round financing and the comprehensive layout of eda2.0 R & D
How to install and use PHP library neo4j
Leetcode 199. right view of binary tree
[3D target detection] 3dssd (II)