Simple understanding of functions

function

Use functions to improve code readability and execution

what is a function

A function is a function, a separate unit of program code that each function uses to accomplish a specific task, and the name of the function is the name of the function

Usually there are input parameters and return values

Classification of functions

Functions are divided into library functions and custom functions (focusing on custom functions)

Library Functions

The C language provides functions that we can use directly

In order to support portability and improve program efficiency, a series of similar library functions are provided in the basic library of C language, which is convenient for programmers to develop software.
Including the common printf function and scanf function is the IO function.

The use of library functions has header files

Here is an example of a simple library function
strcpy

char* strcpy(char* destination, const char* source);

This is how to use the strcpy function obtained from the search, and the header file that can be searched for this function is <string.h>


#include<stdio.h>
#include<string.h>//头文件
int main()
{
    
    
    char arr[20] = "abc";
    char b[20] = {
    
     0 };

    strcpy(b, arr);//括号里面的叫做参数
    //这个函数的返回值是char类型
    printf("%s", b);

    return 0;
}

Search the website for library functions:

Need to learn to use the query tool:
1.MSDN (Microsoft Developer Network)
2.www.cplusplus.com
3.http://en.cppreference.com (English version)
4.http://zh.cppreference.com (Chinese version) Version)

custom function

self-created function

Like library functions, custom functions have function names, return value types, and function parameters.

//定义函数
type name(parameter)
{
    
    
    
}
//定义函数可以没有括号内的参数,但是返回值类型与函数名以及函数名后面的括号不能少

Function name

Specifies the name of the function to be called later

return value type

has return value
#include<stdio.h>
int Add()
{
    
    
    return 9;
}//这是一个自定义的函数,函数名叫做Add,返回值类型是int型的
//return 后面的值就是返回的内容,这个值也可以是表达式
int main()
{
    
    
    int x = 0;
    x = Add();//函数返回值会被赋给x,但是要求x的类型与函数返回类型相同
    printf("%d",x);//9
    return 0;
}
no return value

There are also functions without a return value, so the type entered in the position of the return value should be void, that is:

void func()
{
    
    
    //这中情况下可以有return,也可以没有return,但是都不会返回到主函数里面
}

function parameter

actual parameters

The actual parameters passed to the function are called actual parameters. The
actual parameters can be constants, variables, expressions, functions, etc.
no matter what type of value the actual parameter is. This value is passed to the formal parameter

formal parameters

Formal parameters refer to the variables in parentheses after the function name, because the formal parameters are only instantiated (allocated memory units) in the process of the function being called, so they are called formal parameters. Formal parameters are automatically destroyed when the function call is complete.
So formal parameters are only valid within functions.

 #include<stdio.h>
int Add(int c,int d)//被调函数
    //被调函数里面的参数叫做形参
{
    
    
    return c+d;
}
int main()
{
    
    
    int a = 20;
    int b = 30;
    int x = 0;
    x = Add(a,b);//主调函数
    //这里Add函数括号里就是函数的参数
    //主调函数里面的参数叫做实参
    
    printf("%d",x);//50
    return 0;
}

Can formal parameters be named the same as actual parameters?
Yes, because formal parameters and actual parameters function in different memory units, the scopes are different, and they do not affect each other

Function declaration and definition

Function definition: refers to the establishment of the function function, that is, the code segment starting from the function header and ending with the function body.

A function declaration
tells the compiler what a function is called, what the parameters are, and what the return type is. But whether it exists or not is not determined by the function declaration.
The declaration of a function generally appears before the use of the function. To satisfy the declaration before use.
Function declarations are generally placed in header files.

If the function is defined before the main function, it can be used without a declaration
If the function is defined after the main function, the function needs to be declared before the function can be called

Data passing for function calls

There are two ways to call a function

call by value

Pass the value of the actual parameter to the formal parameter. The formal parameter allocates space when the function starts to call, and stores the value of the actual parameter. In this case, the formal parameter and the actual parameter only have the same value and different addresses. Changes to the value of the formal parameter in the calling function do not affect the actual parameter.

#include<stdio.h>
void Func(int x,)
{
    
    
    x++;
    printf("%d",x);//11
}
int main()
{
    
    
    int a = 10;
    Add(a);
    printf("%d",a);//10
    return 0;
}
call by address

Call by reference is a way to call a function by passing the memory address of a variable created outside the function to the function parameter.
This method of passing parameters allows the function to establish a real connection with the variables outside the function, that is, the function can directly operate the variables outside the function.

#include<stdio.h>
Func(int *pa)
{
    
    
*pa = *pa + 1;    
}
int main()
{
    
    
    int a = 10;
    Func(&a);
    printf("%d",a);//11
    return 0;
}//把变量a的地址存放在指针变量pa里面,后面*pa的操作就是在改变a的值
Exercises on the use of functions

1. Write a function to determine whether a number is prime or not.

//是素数返回1;
//不是素数返回0;
#include<stdio.h>

int is_prime(int n)
{
    
    
	int j = 0;
	for (j = 2; j < n; j++)
	{
    
    
		if (n % j == 0)
		{
    
    
			return 0;//直接返回,程序直接结束
		}
}
	return 1;
}

int main()
{
    
    
	int a = 0;
	int b = 0;
	for (a = 100; a <= 200; a++)
	{
    
    
		if (is_prime(a))
            /*返回0就不打印,返回1就打印*/
		{
    
    
		printf("%d", a);
		}
	}
	return 0;
}

2. Write a function to determine whether a year is a leap year.

#include<stdio.h>

int is_leap_year(int b)
{
    
    
if ((b % 4 == 0 && b % 100 != 0) || b % 400 == 0)
		return 1;
	else
		return 0;
}

int main()
{
    
    
	int a = 0;
	for (a = 1000; a <= 2000; a++)
	{
    
    //判断
		if (is_leap_year(a))
		{
    
    
			printf("%d  ", a);
		}
		
	}
    return 0;
}

3. Write a function to implement a binary search of an integer sorted array

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

int binary_serach(int arr[], int k,int sz) 
{
    
    

	int left = 0;
	int right = sz -1;//最右边的下标是数组元素个数-1

	while (left <= right)
	{
    
    
		int mid = (left + right) / 2;
	
		if (arr[mid] > k)
		{
    
    
			right = mid - 1;
		}
		else if (arr[mid] < k)
		{
    
    
			left = mid + 1;
		}
		else
		{
    
    
			return mid;
		}
	}
	return -1;//找不到了
}


//如果找到了返回下标,找不到返回-1;
int main()
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	int k = 7;
	int sz = sizeof(arr) / sizeof(arr[0]);//可以计算数组元素个数

	int ret = binary_serach(arr,k,sz);
	//数组arr再传参的时候传递的是首元素的地址	--->接收的是指针,大小是4

	if (-1 == ret)
	{
    
    
		printf("找不到\n");
	}
	else
	{
    
    
		printf("找到了\n");
		printf("下标是%d", ret);
	}
	return 0;
}

Nested calls and chained access of functions

nested calls
#include <stdio.h>
void new_line()
{
    
    
 printf("hehe\n");
}
void three_line()
{
    
    
    int i = 0;
 for(i=0; i<3; i++)
   {
    
    
        new_line();//早这个函数中调用new_line函数
   }
}
int main()
{
    
    
 three_line();
 return 0;
}

Functions can be called nested, but not nested definitions

chained access

Use the return value of one function as an argument to another function.

int main()
{
    
    
    printf("%d", printf("%d", printf("%d", 43)));
    //注:printf函数的返回值是打印在屏幕上字符的个数
    //所以结果是4321
    return 0;
}

function recursion

What is recursion? The programming technique in which a program calls itself is called recursion.
Recursion as an algorithm is widely used in programming languages.
A procedure or function in its definition or description has a method of directly or indirectly calling itself, which usually transforms a large and complex problem into a smaller problem similar to the original problem to solve. The
recursive strategy only A small number of programs can be used to describe the repeated calculations required for the problem-solving process, which greatly reduces the code amount of the program.
The main way of thinking about recursion is: make big things small
Two necessary conditions for recursion
There are restrictions, when the restrictions are met, the recursion will not continue.
It gets closer and closer to this limit after each recursive call.

Exercises on Function Recursion

Takes an integer value (unsigned) and prints its bits in order. For example: 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()
{
    
    
 int num = 1234;
 print(num);
 return 0;
}

find the factorial of n



#include<stdio.h>
int func(int n)
{
    
    
    if (n == 1)
        return 1;
    else
        return n * func(n - 1);
}

int main()
{
    
    

    int n = 0;
    scanf("%d", &n);
    int ret = 0;
    ret  = func(n);
    printf("%d", ret);

    return 0;
}

Recursively implement strlen function



#include<stdio.h>

int my_strlen(char *s)
{
    
    
    if (*s == '\0')
        return 0;
    else
        return 1 + my_strlen(s+1);
}
int main()
{
    
    
    char arr[] = "abcd";
    int len = 0;
    len = my_strlen(arr);
    printf("%d", len);

    return 0;
}

Calculate Fibonacci numbers



#include<stdio.h>

int fib(int n)
{
    
    
    if (n <= 2)
        return 1;
    else
        return fib(n - 1) + fib(n - 2);
}
int main()
{
    
    

    int n = 0;
    int num = 0;
    scanf("%d", &n);
    num = fib(n);
    printf("%d", num);
    return 0;
}

else
return 1 + my_strlen(s+1);
}
int main()
{ char arr[] = “abcd”; int len = 0; len = my_strlen(arr); printf("%d", len);



return 0;

}


计算斐波那契数

```c


#include<stdio.h>

int fib(int n)
{
    if (n <= 2)
        return 1;
    else
        return fib(n - 1) + fib(n - 2);
}
int main()
{

    int n = 0;
    int num = 0;
    scanf("%d", &n);
    num = fib(n);
    printf("%d", num);
    return 0;
}

Guess you like

Origin blog.csdn.net/cainiaochufa2021/article/details/121214674