Functions of c language

Posted by ame12 on Thu, 16 Dec 2021 05:23:11 +0100

This book has a lot of references to c primer, which is mainly for review

preface

It can be said that function is extremely important in c language. We will certainly deal with it in programming. For example, when we use library functions: scanf and printf, these are the functions designed by the boss, which are very comfortable for us to use. However, we also need to design our own functions to deal with various requirements.

c function

Let's look at the definition of function:

Don't worry about understanding this definition. It's very important for us to write functions in the compiler.
Let's look at an example of using functions to make the code of programming clearer

#include<stdio.h>
#define MAXSIZE 100 / / the maximum capacity of the array
void Input(int* arr,int num);// Enter elements into the array
void Output(int* arr,int num);//Elements of the output array 
int main(){
	   /*
				*  Design function 
				*  1,Enter elements into the array
				*  2,Print elements inside an array 
				*/
				//Initialize element 
				int array[MAXSIZE]={0};
				int size=0; 
				
				printf("Your array size is:");
				scanf("%d",&size);
				printf("\n Please enter the elements of the array you want to enter:"); 
    Input(array,size);//input data
    printf("\n Now output the elements of the array:");
    Output(array,size);//output data
	
	
	return 0;
} 
void Input(int* arr,int num)// Enter elements into the array
{
    for(size_t i=0;i<num;i++){
    	scanf("%d",&arr[i]);
				} 

} 
void Output(int* arr,int num)//Elements of the output array
{
	 for(size_t i=0;i<num;i++){
	 	printf("%d ",arr[i]);
		}
} 

The following code operates in a main function:

#include<stdio.h>
#define MAXSIZE 100
int main(){
	
	  //Initialize element 
				int array[MAXSIZE]={0};
				int size=0; 
				
				printf("Your array size is:");
				scanf("%d",&size);
				printf("\n Please enter the elements of the array you want to enter:"); 
				 for(size_t i=0;i<size;i++){
    	scanf("%d",&array[i]);
				} 
				printf("\n Now output the elements of the array:");
				for(size_t i=0;i<size;i++){
	    	printf("%d ",array[i]);
		                         }
	
	return 0; 
	} 

We can clearly see that each function performs a function, which is very clear. In addition, if the function is not written properly, we can immediately see where the error point is.

Characteristics of function

In c language, when using function, it includes function prototype, function definition and calling function
Look at the picture:

Function call:

Functions provide a black box perspective. When using functions, we don't need to understand how the function body is written, just like ordinary people sitting on the high-speed railway, we don't need to know how the high-speed railway is built, which of course provides a convenience for programmers.

Initial recursion

When a function calls itself, this process is called recursion. This concept is very vague, bloggers have limited ability, so I won't introduce it in detail.

The author of this book gives a recursive code (blogger makes some modifications) (source: c primer plus):

/* recur.c -- recursion illustration */
#include <stdio.h>
void func(int);//Declaration of function 
int main(void)
{
    func(1);
    return 0;
}
void func(int n)//Definition of function 
{
    printf("Level %d: n location %p\n", n, &n); // 1
    if (n < 4)
    func(n+1);
    printf("LEVEL %d: n location %p\n", n, &n); // 2  
}

Note: don't jump into recursion, otherwise our brain is hard to think.

Let's take a look at some small examples of using recursion. You can experience the advantages and disadvantages of recursion:

/* binary.c -- prints integer in binary form */
#include <stdio.h>
void to_binary(unsigned long n);
int main(void)
{
    unsigned long number;
    printf("Enter an integer (q to quit):\n");
    while (scanf("%lu", &number) == 1)//Judge whether the input is true according to the state of the input stream
    {
        printf("Binary equivalent: ");
        to_binary(number);
        putchar('\n');
        printf("Enter an integer (q to quit):\n");
    }
    printf("Done.\n");
    return 0;
}
void to_binary(unsigned long n)   /* recursive function */
{
    int r=0
    r = n % 2;// r is constantly assigned -- > the remainder of N% 2
    if (n >= 2)//As long as the number is greater than or equal to 2, it still has binary bits
    to_binary(n / 2);
     putchar(r == 0 ? '0' : '1');
    return;
}

Calculate the number of combinations:
A property of Combinatorial Number: C (n, m) = C (n − 1, m) + C (n − 1, m − 1)
There are two other exceptions:

Look at the code:

#Include < iostream > / / calculate the number of combinations 
using namespace std;
long long Cnr(int a,int b) ;
const int maxn =100+10;
long long dp[maxn][maxn];
int main ( ){
	int a,b;
	while(cin>>a>>b){
	cout<<Cnr(a,b)<<endl;
	}
	
	return 0;
}
long long  Cnr(int a,int b){
	if(dp[a][b]!=0){
		return dp[a][b];
	}if(b==0||a==b){
		return 1;
	}
	return dp[a][b]=Cnr(a-1,b)+Cnr(a-1,b-1);//The combination number formula is derived
}

Calculate factorial:
The recurrence formula for factorial is:

Code source: (c primer plus)

// factor.c -- uses loops and recursion to calculate factorials
#include <stdio.h>
long fact(int n);
long rfact(int n);
int main(void)
{
    int num;
    printf("This program calculates factorials.\n");
    printf("Enter a value in the range 0-12 (q to quit):\n");
    while (scanf("%d", &num) == 1)
    {
        if (num < 0)
            printf("No negative numbers, please.\n");
        else if (num > 12)
            printf("Keep input under 13.\n");
        else
        {
            printf("loop: %d factorial = %ld\n",
                   num, fact(num));
            printf("recursion: %d factorial = %ld\n",
                   num, rfact(num));
        }
        printf("Enter a value in the range 0-12 (q to quit):\n");
    }
    printf("Bye.\n");
    
    return 0;
}

long fact(int n)     // loop-based function
{
    long ans;
    for (ans = 1; n > 1; n--)
        ans *= n;
    return ans;
}

long rfact(int n)    // recursive version
{
    long ans;
    if (n > 0)
        ans= n * rfact(n-1);
    else
        ans = 1;
    return ans;
}

Recursively calculate Fibonacci sequence:
Let's look at the recurrence formula of Fibonacci sequence:

We can write a recursive function according to the code:

#include<stdio.h>
#include<stdlib.h>
#define MAX 100

long Fibonacci(long n); 
long Fibonacci_1(long n);
long Fibonacci_2(long n);
long Fibonacci_3(long n);
int main(){
	   printf("%d\n",Fibonacci(7));
	   printf("%d\n",Fibonacci_1(7));
	   printf("%d\n",Fibonacci_2(7));
	   printf("%d\n",Fibonacci_3(7));
	return 0;
} 
long Fibonacci(long n)
{
	  if(n==1||n==2)return 1;
	  else return Fibonacci(n-1)+Fibonacci(n-2); //Double recursion consumes a lot of computer memory! Not advocate 
	
}
long Fibonacci_1(long n){
        int* array=(int *)malloc(sizeof(int)*MAX);  //Dynamic memory allocation. The variables allocated in the heap area are nameless parameters and should be received with pointers     
	        array[0]=array[1]=1;
			for(int i=2;i<n;i++){
		array[i]=array[i-1]+array[i-2];
							   }  
         int sum=array[n-1];
			free(array);
			return sum; 
}
long Fibonacci_2(long n){
	  int a=1;
	  int b=1;
	  int c=1;
	  while(n>2){
	  	c=a+b;
	  	a=b;
	  	b=c;
	  	n--;
			}
return c;
}
long Fibonacci_3(long n){
	  if(n<=2)return 1;
	  int F=0,F1=1,F2=1;
	  for(int i=3;i<=n;i++){
	  	F=F1+F2;
	  	F1=F2;
	  	F2=F;
			             }
	return F;
}
}

Bloggers also read books to record their knowledge, and their ability is limited. Let's take a look at the high-quality summary of c language functions written by other bloggers of CSDN:
1,Function -- C language programming
2,[initial level of C language] the most complete function explanation of epic works in the whole network (whole process dry goods + recommended Collection)
Are you curious about the parameters of the main function? Take a look at this 1 article!
3,[C/C + + basics] parameters argc and argv of main function
4. What is the difference between c and c + + functions? There are only two kinds of c language and three kinds of c + +. Come and have a look at this article!
[ ❗ Focus! There are only two ways to transfer function parameters in C language (value transfer and address transfer). Reference transfer is not supported! ❗]

Topics: C