IV. C language Β· all-round understanding of functions

πŸŒ• Write in front

  • 🍊 Blog home page: kikoking's Jianghu background
  • πŸŽ‰ Welcome to pay attention πŸ”Ž give the thumbs-up πŸ‘ Collection ⭐ Leave a message πŸ“
  • 🌟 This article is original by kikokingzz and launched by CSDN!
  • πŸ“† Starting time: 🌹 November 21, 2021 🌹
  • πŸ†• Last updated: πŸŽ„ November 21, 2021 πŸŽ„
  • βœ‰οΈ Persistence and hard work will surely bring poetry and distance!
  • πŸ™ The author's level is very limited. If you find an error, please leave a message! Thank you very much!

πŸ‰: This article contains a comprehensive understanding of C language functions, and is equipped with corresponding example understanding. Later, special exercises and problem brushing plates will be updated!

50: Daxian, finally come to the function plate!

πŸ‰: yep! Boy, this chapter contains a lot of content. Read it carefully!

catalogue

πŸŒ• Write in front

πŸ”₯ 1. What is the function?  

πŸ”₯ two point one   Library function

πŸŒ• 2.1.1 why are there library functions?

πŸŒ• 2.1.2 how to learn to use library functions?

πŸŒ™ Self study case 1-strcpy function self study

πŸŒ™ Self study case 2-memset self study

πŸŒ™ Self study case 3-strlen

πŸ”₯ 2.2 user defined functions

πŸŒ• 2.2.1 composition of user-defined functions

πŸŒ• 2.2.2 typical cases

πŸŒ™ 1. Write a function to find the maximum value of two integers

πŸŒ™ 2. Write a function to exchange the contents of two integer variables

πŸ”₯ 3. Parameters of function

πŸŒ• 3.1 actual parameters (actual parameters)

πŸŒ• 3.2 formal parameters (formal parameters)

πŸ”₯ 4. Function call

πŸŒ• 4.1 value transfer call

πŸŒ• 4.2 address calling

πŸ”₯ Function call case

πŸŒ™ 1. Judge whether a function is a prime number

πŸŒ™ 2. Write a function to judge whether it is a leap year

πŸŒ™ 3. Write a function to realize the binary search of an integer ordered array.

πŸŒ™ 4. Write a function. Every time this function is called, the value of num will be increased by 1

πŸ”₯ Function return type

πŸ”₯ 5. Nested call and chained access of functions

πŸŒ• 5.1 nested calls

πŸŒ• 5.2 chain access

πŸŒ• 3. Exercises

  πŸ”₯ 6. Function declaration and definition

πŸŒ• 6.1 function definition

πŸŒ• 6.2 function declaration

πŸŒ™ If the company writes code, will it write all the code in test.c?

πŸ”₯ 7. Function recursion

πŸŒ• 7.1 what is recursion?

🍊 Exercise 1. Receive an integer value (unsigned) and print its bits in order

  πŸŒ• 7.2 two necessary conditions for recursion

🍊 Exercise 2. Writing a function does not allow the creation of temporary variables. Find the length of the string

🍊 Exercise 3   Factorization of n (without overflow)

🍊 Exercise 4. Find the nth Fibonacci number (without considering overflow)

πŸ”₯ 1. What is the function?  

  1. In computer science, subroutine (English: subroutine, procedure, function, routine, method, subroutine, callable unit) is a part of code in a large program, which is composed of one or more statement blocks. It is responsible for completing a specific task and has relative independence compared with other codes.
  2. Generally, there are input parameters and return values, which provide encapsulation of the process and hiding of details. These codes are usually integrated into software libraries

✨✨✨ I am the dividing line ✨✨✨

πŸ”₯ two point one   Library function

πŸŒ• 2.1.1 why are there library functions?

  1.   We know that when we learn C language programming, we always can't wait to know the result after a code is written, and want to print the result to our screen. At this time, we will frequently use a function: print information to the screen (printf) according to a certain format.
  2. In the process of programming, we will frequently do some string copy (strcpy).

·Like the basic functions we described above, they are not business code. In order to support portability and improve program efficiency, a series of similar library functions are provided in the basic library of C language to facilitate programmers' software development.

πŸŒ• 2.1.2 how to learn to use library functions?

  • You need to learn how to use query tools:
  • MSDN(Microsoft Developer Network)
  • www.cplusplus.com
  • http://en.cppreference.com (English version)
  • http://zh.cppreference.com (Chinese version)

πŸŒ™ Self study case 1-strcpy function self study

·Search for strcpy in MSDN

·Understand function definition methods, return values, parameters, etc

#include<stdio.h>
#include<string.h>
int main()
{
    //strlen--string length -- related to string length
    //strcpy--string copy -- string copy
    char arr1[] = "bit";//Original data
    char arr2[] = "#########"; / / destination string
    //             bitBit \ 0  is the end flag when printing
    strcpy(arr2, arr1);
    printf("%s\n", arr2);
    return 0;
}

πŸŒ™ Self study case 2-memset self study

·Search for memset in MSDN

·Understand function definition methods, return values, parameters, etc

#include<stdio.h>
int main()
{
    char arr[]="hello world";
    memset(arr,'*',5);
    //arr - the address of this array space
    //Put '*' here because it stores ASCII values and integer values (int type)
    printf("%s\n",arr);//%s print string
    //***** world
    return 0;
}

πŸŒ™ Self study case 3-strlen

 · Search for memset at www.cplusplus.com

·Understand function definition methods, return values, parameters, etc

#include<stdio.h>
#include<string.h>
int main()
{
	char arr[] = "abc";
	size_t len = strlen(arr);
	printf("%u\n", len);
	//%d-signed
	//%u-unsigned
	return 0;
}

✨✨✨ I am the dividing line ✨✨✨  

πŸ”₯ 2.2 user defined functions

50: Make good use of library functions. Do we just need to master library functions?

πŸ‰: If library functions can do everything, what do programmers have to do? So more importantly, custom functions!

πŸŒ• 2.2.1 composition of user-defined functions

·Like library functions, custom functions have function names, return value types and function parameters. However, the difference is that these are designed by ourselves, which gives programmers a lot of room to play.
Β 

·Composition of function:

Β 

πŸŒ• 2.2.2 typical cases

πŸŒ™ 1. Write a function to find the maximum value of two integers

#include<stdio.h>
int getmax(int x, int y)
{
    if (x > y)
        return x;
    else
        return y;
}
int main()
{
    int a = 10;
    int b = 20;
    //Use of functions
    int max = getmax(a, b);
    int max1 = getmax(100, 300+1);
    printf("%d\n", max1);
    return 0;
}

πŸŒ™ 2. Write a function to exchange the contents of two integer variables

❌ Error demonstration:

#include<stdio.h>
void Swag(int x, int y)//void indicates that there is no return value
{
    int z = x;
        x = y;
        y = z;
}
int main()
{
    int a = 10;
    int b = 20;
    int tmp;
    printf("a=%d b=%d\n", a, b);
    Swag(a, b);
    printf("a=%d b=%d\n", a, b);
    return 0;
}

50: Why is it clear that the two values in the Swag function are exchanged, but the final result is not exchanged?

πŸ‰: Boy, take a closer look at the example in the figure above. The addresses of formal parameters x and y in the Swag function are different from those of arguments a and b. We just exchange the two values in the Swag function. In fact, for a and b, they do not change

πŸ‰: That is, when a function is called, the argument is passed to the formal parameter, which is actually a temporary copy of the argument. Therefore, the modification of the formal parameter will not affect the argument

50: So how to modify it?

πŸ‰: We just need to pass the addresses of arguments a and b to formal parameters x and y through the pointer, and then we can succeed through the dereference operation

βœ… Positive solution (address):

#include<stdio.h>
void Swag(int* pa, int* pb)//void indicates that there is no return value
{
    int tmp = 0;
    tmp = *pa;//Dereference operation with
    *pa = *pb;
    *pb = tmp;
}
int main()
{
    int a = 10;
    int b = 20;
    int tmp;
    printf("a=%d b=%d\n", a, b);
    Swag(&a, &b);
    printf("a=%d b=%d\n", a, b);
    return 0;
}

✨✨✨ I am the dividing line ✨✨✨

πŸ”₯ 3. Parameters of function

πŸŒ• 3.1 actual parameters (actual parameters)

  1. The parameters really passed to the function are called arguments.
  2. Arguments can be constants, variables, expressions, functions, etc.
  3. No matter what type of arguments are, they must have definite values when making a function call in order to pass these values to the formal parameters.

πŸŒ• 3.2 formal parameters (formal parameters)

  1. Formal parameters refer to the variables in parentheses after the function name. They are called formal parameters because they are instantiated (memory units are allocated) only when the function is called.
  2. Formal parameters are automatically destroyed when the function call is completed. Therefore, formal parameters are only valid in functions.
  3. When an argument is passed to a formal parameter, the formal parameter is actually a temporary copy of the argument, and the modification of the formal parameter will not change the argument (such as the misinterpretation in the exchange of digital cases)

  1. The parameters x, y, px and py in the above Swap1 and Swap2 functions are formal parameters.
  2. Num1 and num2 passed to Swap1 in the main function and & num1 and & num2 passed to Swap2 function are actual parameters.

·Here you can see that when the Swap1 function is called, x   As like as two peas, y has its own space (value calling), and has the same content as the real reference. So we can simply think that after the formal parameter is instantiated, it is actually equivalent to a temporary copy of the argument.

✨✨✨ I am the dividing line ✨✨✨

πŸ”₯ 4. Function call

πŸŒ• 4.1 value transfer call

  • The formal parameters and arguments of the function occupy different memory blocks (different memory addresses), and the modification of the formal parameters will not affect the arguments.
void Swag(int x, int y)//void indicates that there is no return value
{
    int z = x;
        x = y;
        y = z;
}

πŸŒ• 4.2 address calling

  • Addressing call is a way to call a function by passing the memory address of the variable created outside the function to the function parameters.
  • This parameter transfer method can establish a real relationship between the function and the variables outside the function, that is, the variables outside the function can be directly operated inside the function.
void Swag(int* pa, int* pb)//void indicates that there is no return value
{
    int tmp = 0;
    tmp = *pa;//Dereference operation with
    *pa = *pb;
    *pb = tmp;
}

Β 

πŸ”₯ Function call case

πŸŒ™ 1. Judge whether a function is a prime number

#include<stdio.h>
#include<math.h>

int is_prime(int n)//If it is a prime number, return 1. If it is not a prime number, return 0
{
    for (int j = 2; j <= sqrt(n); j++)//Write the optimized method sqrt(n)
    {
        if (n % j == 0)//Divided by j
            return 0;
    }
    return 1;
}
int main()
{//Print prime numbers between 100-200
    int i = 0;
    for (i = 100; i <= 200; i++)//Generate a number of 100-200
    {
        //Judge whether i is prime
        if (is_prime(i) == 1)
            printf("%d\n", i);
    }
}

πŸŒ™ 2. Write a function to judge whether it is a leap year

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

//Returns 1 for leap years, not 0 for leap years
int is_leap_year(int x)
{
	if(((x % 4 == 0) && (x % 100 != 0))||(x % 400 == 0))
	    return 1;
	else
		return 0;
}

int main()
{
	int count = 0;
	int y = 0;
	for (y = 1000; y <= 2000; y++)
	{
		//Judge whether y is a leap year
		if (is_leap_year(y))
		{
			count++;
			printf("%d\n", y);
		}
	}
	printf("%d Leap year\n", count);
	return 0;
}

πŸŒ™ 3. Write a function to realize the binary search of an integer ordered array.

Important: when the array is passed to the formal parameter, the first element address is passed

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

int binary_search(int arr[], int k,int num)
{
	//Find in half
	//int num = sizeof(arr) / sizeof(arr[0]);
	//       Pointer size = = 4 / 4 = 1
	int left = 0;
	int right = num - 1;
	do 
	{
		int mid = (left + right) / 2;
		if (arr[mid] < k)
		{
			left = mid + 1;
		}
			
		else if (arr[mid] > k)
		{
			right = mid - 1;
		}
		else
			return mid;//eureka

	}while(left<=right);
	return -1;
}

//If found, return the subscript
//Return - 1 if not found
int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int k = 7;
	int num = sizeof(arr) / sizeof(arr[0]);
	//Pass array arr to binary_ The search function actually passes the address of the first element of arr
	int ret =binary_search(arr,k,num);
	if (-1 == ret)
		printf("can't find\n");
	else
		printf("Yes, the subscript is%d", ret);

	return 0;
}

πŸŒ™ 4. Write a function. Every time this function is called, the value of num will be increased by 1

·Method 1. Need to change the argument - Address

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

void add(int* p)
{
	++*p;
}

int main()
{
	int num = 0;
	add(&num);
	printf("%d", num);
	add(&num);
	printf("%d", num);
	add(&num);
	printf("%d", num);
	return 0;
}

·Method 2. Do not use parameter passing and adopt frequent assignment

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

int add(int m)
{
	return m + 1;
}

int main()
{
	int num = 0;
	num=add(num);//Frequent assignment
	printf("%d", num);
	num = add(num);
	printf("%d", num);
	num = add(num);
	printf("%d", num);
	return 0;

}

✨✨✨ I am the dividing line ✨✨✨

πŸ”₯ Function return type

  1. Void - no return (you can use return; to end the void function)
  2. char int float - the return value is its corresponding type
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void test1()
{
	int n = 5;
	printf("hehe\n");
	if (n == 5)
		return;//Use return in void; To return
	//You can terminate the function in advance
	printf("haha\n");
}
int test2()
{
	return 1;
}

int main()
{
	test1();
	return 0;
}

✨✨✨ I am the dividing line ✨✨✨  

πŸ”₯ 5. Nested call and chained access of functions

πŸŒ• 5.1 nested calls

·Functions can be called nested; Nested definitions are not allowed
//Functions cannot be nested
void test1()
{
	void test2()
	{

	}
}

//But you can nest calls
void test1()
{
	test2();
}

πŸŒ• 5.2 chain access

·Take the return value of one function as an argument to another function

int main()
{
	int len = strlen("abc");
	printf("%d\n", len);
	printf("%d\n", strlen("abc"));
	//Take the return value of strlen function as the parameter of printf function
	return 0;
}

πŸŒ• 3. Exercises

·Consider chained access -- take the return value of one function as an argument to another function

int main()
{
	printf("%d", printf("%d", printf("%d", 43)));
	//What's the result?
	//Note: the return value of the printf function is the number of characters printed on the screen
	return 0;
}

  Previously on: learn about the return value of the printf function

  πŸ”₯ 6. Function declaration and definition

πŸŒ• 6.1 function definition

·The definition of function refers to the specific implementation of the function and explains the function implementation of the function.

·Solution: (add a function declaration)

ADD(int x, int y);//Function declaration

int main()
{
	int a = 10;
	int b = 20;
	int ret = ADD(a, b);
	printf("%d", ret);

	return 0;
}

int ADD(int x, int y)
{
	int z = x + y;
	return z;
}

πŸŒ• 6.2 function declaration

1. Tell the compiler what a function is called, what the parameters are and what the return type is. But whether it exists or not depends on the function declaration.

2. The declaration of a function usually appears before the use of the function. To meet the requirements of declaration before use.

3. The function declaration is generally placed in the header file (. h file).

·Essential application: stripping out

//add.h function declaration

#include<stdio.h>
int ADD(int x, int y);
//add.c function definition

#include"add.h"
int ADD(int x, int y)
{
	int z = x + y;
	return z;
}
//test.c main function

#include"add.h"
int main()
{
	int a = 10;
	int b = 20;
	int ret = ADD(a, b);
	printf("%d", ret);

	return 0;
}

In the above, add.c and add.h are collectively referred to as the addition module

πŸŒ™ If the company writes code, will it write all the code in test.c?

1. Write the function module! The efficiency is greatly improved

2. You can use static libraries to sell functions

#define _CRT_SECURE_NO_WARNINGS 1
#include"add.h"
#include<stdio.h>

#pragma comment(lib,"add.lib") / / use static library
int main()
{
	int a = 10;
	int b = 20;
	printf("%d", ADD(10, 20));
	return 0;
}

✨✨✨ I am the dividing line ✨✨✨  

πŸ”₯ 7. Function recursion

πŸŒ• 7.1 what is recursion?

·The programming technique of a program calling itself is called recursion

·Function recursion: the function calls itself

·As an algorithm, recursion is widely used in programming languages. A method in which a procedure or function 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

·The recursive strategy only needs a small number of programs to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code of the program.

The main way of thinking about recursion is to make big things small

🍊 Exercise 1. Receive an integer value (unsigned) and print its bits in order

·For example: input: 1234   οΌ› Output 1 2 3 4

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

Print(unsigned int n)
{
	if (n > 9)
	{
		Print(n / 10);//Print(123) 1 2 3
	}
	printf("%d\t", n % 10);//

}

int main()
{
	unsigned int num = 0;
	scanf("%d", &num);//Print each bit sequentially 
	Print(num);
}

  Drawing understanding:

  πŸŒ• 7.2 two necessary conditions for recursion

1. There is a constraint. When this constraint is met, recursion will not continue.

2. Get closer and closer to this limit after each recursive call.

πŸ“ Tip1. Each function call will apply for a piece of memory space in the stack area of memory

·The stack space allocated by the system to the program is limited, but if there is an dead loop or (dead recursion), it may lead to the continuous development of stack space and eventually the depletion of stack space. This phenomenon is called stack overflow

Β πŸ“Tip2.stackoverflow - Programmer's version of knowledge

🍊 Exercise 2. Writing a function does not allow the creation of temporary variables. Find the length of the string

·Solution 1. Use temporary variables (not meeting the requirements of this problem)

int my_strlen(char* s)//s is equivalent to pointing to a in the string
{
	int count = 0;//Temporary variable
	while (*s != '\0')
	{
		count++;
		s++;//The pointer to char * is a byte
		//The address sequence + 1 can jump to the next character
        //If it is an int pointer, it needs + 4 to jump to the next character
	}
	return count;

}

int main()
{
	//Find string length
	char arr[] = "abc";
	int len = my_strlen(arr); 
	//A B C in arr \ 0
	//arr is the array name. The array name is the address of the first element of the array
	printf("%d", len);
	return 0;

}

·Solution 2. Use function recursion

Idea:
my_strelen("abc");
1+my_strelen("bc");
1+1+my_strelen("c");
1+1+1+my_strelen("\0");
1+1+1+0=3
int my_strlen(char* s)//s is equivalent to pointing to a in the string
{
	int count = 0;
	while (*s != '\0')
	{
		count++;
		s++;//The pointer to char * is a byte
		//Add 1 to the address sequence to change to the next character
	}
	return count;

}

int my_strlen(char* s)//s contains the address of a
{
	if (*s == '\0')
		return 0;
	else
		return 1 + my_strlen(s + 1);//s+1 is the address of b

Note understanding:

🍊 Exercise 3   Factorization of n (without overflow)

·Solution 1. Circular solution

int main()
{
	int n = 0;
	int ret = 1;
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i)
	{
		ret *= i;
	}
	printf("%d", ret);
	return 0;
}

·Solution 2. Recursive method

int fac(int n)
{
	if (n <= 1)
		return 1;
	else
		return n * fac(n - 1);
}

int main()
{
	int n = 0;
	scanf("%d", &n);
	int ret = fac(n);
	printf("%d", ret);
	return 0;
}

🍊 Exercise 4. Find the nth Fibonacci number (without considering overflow)

·Solution 1. Recursion

int count = 0;

int fib(int x)
{
	if (x == 3)//Let's see how many times it takes to calculate 3
		count++;
	if (x <= 2)
		return 1;
	else
		return fib(x - 1) + fib(x - 2);
}

int main()
{
	int n = 0;
	scanf("%d", &n);
	int ret = fib(n);
	printf("The first%d The Fibonacci number is%d\n", n,ret);
	return 0;
}

 · Solution 2. Loop method (from front to back)

int fib(int x)
{
	int a = 1;
	int b = 1;
	int c = 1;

	while (x>2)
	{
		c = a + b;
		a = b;
		b = c;
		x--;
	}
	return c;
}

int main()
{
	int n = 0;
	scanf("%d", &n);
	int ret = fib(n);
	printf("The first%d The Fibonacci number is%d\n", n,ret);
	return 0;
}

  πŸ“ Tip3. Positive overflow of complement number

Tags: C Programming Back-end function

Posted on Sun, 21 Nov 2021 15:11:59 -0500 by ganeshasri