# C language programming -- Summary of learning knowledge

Keywords: C

----------------------------

# array

## Definition and reference of one-dimensional array

Define a one-dimensional array (type specifier array name [constant expression] is similar to int a )
1. Continuously allocate storage space for n variables
2. All variable data types must be the same
3. The byte size occupied by all variables must be equal
Operations on one-dimensional data

Initialization complete initialization int a  = {1, 2, 3, 4, 5}
Incomplete initialization. The uninitialized element is 0 int a  = {1, 2}
Not initialized, all elements are garbage value int a 
Reset int a  = 0

Note: only when the array is defined can the overall assignment be made. In other cases, the overall assignment is wrong
There are also assignment, sorting, inversion, maximum / minimum value, search, insert, delete, etc

## Program example of one-dimensional array

Example 1: using array to solve the problem of finding Fibonacci sequence

```#include <stdio.h>

void main()
{
int i;
int f={1,1};
for(i = 2; i < 20; i++)
f[i]=f[i-2]+f[i-1];//Fibonacci sequence formula
for(i = 0; i < 20; i++)
{
if(i%5 == 0)
printf("\n");
printf("%12d",f[i]);
}
}

```

Example 2: Method 1: bubble method to sort 10 numbers

```# include <stdio.h>

void main()
{
int a;
int i,j,t;
printf("input 10 numbers :\n");
for(i=0; i<10; i++)
scanf("%d",&a[i]);
printf("\n");
for(j=0; j<9; j++)//Carry out 9 cycles to achieve 9 comparisons
for(i=0; i<9-j; i++)//Make 9-i comparisons in each trip
if(a[i] > a[i+1])//From small to large / / if (a [i] < a [i + 1]) from large to small
{
t = a[i];
a[i] = a[i+1];
a[i+1] = t;
}
printf("the scorted numbers :\n");
for(i=0; i<10; i++)
printf(" %d",a[i]);
printf("\n");
}
```

Method 2: 10 numbers were sorted by selection method

```# include <stdio.h>

void main()
{
int a;
int i,j,t;
printf("input 10 numbers :\n");
for(i=0; i<10; i++)
scanf("%d",&a[i]);
printf("\n");
for(i=0; i<=9; i++)
for(j=i+1; j<10; j++)
if(a[i] > a[j])//From small to large / / if (a [i] < a [i + 1]) from large to small
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
printf("the scorted numbers :\n");
for(i=0; i<10; i++)
printf(" %5d",a[i]);
printf("\n");
}
```

Example 3: for the problem of binary conversion, input the number (num) to be converted and some converted base from the terminal, and output it according to the input requirements

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

void main()
{
int num ,base;
int a,i=0;
scanf("%d",&num);
scanf("%d",&base);
do
{
a[i]=num%base;
num=num/base;
i++;
}
while(num!=0);
for(i--;i>=0;i--)
{
if(a[i]>=10)
printf("%c",a[i]-10+'A');
else
printf("%d",a[i]);
}
printf("\n");

}
```

## Definition and reference of two-dimensional array

Define 2D array: type specifier array name [constant expression] [constant expression]
initialization

int a;// The default storage type is auto, random value
int a={{3,4,5},{6,7,8}};// All elements are initialized by line
int a={3,4,5,6,7,8};// Initialization of all elements
int a[]{3,4,5,6,7,8};// When all elements are initialized, the row mark can be ignored
int a[]={3,4,5,6,7,8};//FFFFFF error! Column labels cannot be omitted at any time
int a={{3},{7,8}};// Partial element initialization 3,0,0 7,8,0
inta={3,7,8};// Partial element initialization 3,7,8 0,0,0
static int a;// Static modification 0,0,0,00

## Two dimensional array program example

Example 1. Swap the row and column elements of a two-dimensional array A and store them in another two-dimensional array b. 4

```# include <stdio.h>

void main()
{
int a={{1,2,3},{4,5,6}};
int b,i,j;
printf("array a:\n");
for(i=0; i<=1; i++)
{
for(j=0; j<=2; j++)
{
printf("%5d", a[i][j]);
b[j][i] = a[i][j];
}
printf("\n");
}
printf("array b :\n");
for(i=0; i<=2; i++)
{

for(j=0; j<=1; j++)
{
printf("%5d", b[i][j]);
}
printf("\n");
}

}
```

Similar to example 1

```/* Write a program to realize the transpose of matrix (3 rows and 3 columns) (i.e. row column conversion).
For example, if you enter the following matrix:
100 200 300
400 500 600
700 800 900
Program output:
100 400 700
200 500 800
300 600 900*/
# include <stdio.h>

void main()
{
int a,i,j,t;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
scanf("%d",&a[i][j]);
for(i=0; i<3; i++)
for(j=0; j<i; j++)//for(j=i;j<3;j++)
{
t = a[i][j];
a[i][j] = a[j][i];
a[j][i] = t;
}

for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%5d", a[i][j]);
}
printf("\n");

}
}
```

Example 2. Define a two-dimensional array of N*N (N is 4), display it in matrix form after assignment by keyboard, and then multiply the value in the upper right half angle element of the array by m (m keyboard assignment).

```# include <stdio.h>

# define N 4

void main()
{
int a[N][N],i,j,m;
for(i=0; i<N; i++)
for(j=0; j<N; j++)
scanf("%d", &a[i][j]);
scanf("%d",&m);
for(i=0; i<N; i++)
for(j=0; j<N; j++)
printf("%5d", a[i][j]);
printf("\n\n");
for(i=0; i<N; i++)
for(j=i; j<N; j++)
{
a[i][j] = a[i][j]*m;//Upper right corner

}

for(i=0; i<N; i++)
for(j=0; j<N; j++)
printf("%5d", a[i][j]);
printf("\n\n");

}
```

Example 3. Sort each row of a four row and four column two-dimensional array. Even rows (0 as an even number) are sorted from small to large, and odd rows are sorted from large to large
Small sort. For example, two-dimensional array: int a   = {15,4,2,16}, {12,7,9,6}, {8,14,11,5}, {3,10,1,13};, After row
The following sequence is: {2,4,15,16}, {12,9,7,6}, {5,8,11,14}, {13,10,3,1}.

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

void main()
{
int a= {{15,4,2,16},{12,7,9,6},{8,14,11,5},{3,10,1,13}};
int i,j,t,k;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%d ",a[i][j]);
printf("\n\n");
}
for(i=0;i<4;i++)
{
if(i%2==0)
{
for(j=0; j<4; j++)
for(k=j+1;k<4;k++)
if(a[i][j] > a[i][k])
{
t = a[i][j];
a[i][j] = a[i][k];
a[i][k] = t;
}

}
else
{
for(j=0; j<4; j++)
for(k=j+1;k<4;k++)
if(a[i][j] < a[i][k])
{
t = a[i][j];
a[i][j] = a[i][k];
a[i][k] = t;
}
}
}

for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%d ",a[i][j]);
printf("\n\n");
}

}
```

Yang Hui triangle

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

void main()
{
int a={0},i,j;
for(i=0;i<10;i++)
{
a[i]=1;
for(j=1;j<i;j++)
a[i][j]=a[i-1][j-1]+a[i-1][j];
a[i][j]=1;

}
for(i=0;i<10;i++)
{
for(j=0;j<=i;j++)//Lower left half angle
printf("%4d",a[i][j]);
printf("\n");
}
/*for(i=0;i<10;i++)
for(j=i;j<10;j++)Upper right half angle*/
}

```

## Character array

### character string

It is composed of 0 or more characters enclosed in double quotation marks and escape characters. The storage feature is that the end 0 is used as the end mark, and the end 0 is' \ 0 ', which is called an empty character

### Character array definition and initialization

char str = {a ',' b ',' c ','d', 'e'} / / single character assignment
char str = {"alan"} / / String assignment
char str [] = "alan" / / String assignment

### Input and output

Select the input / output function according to the contents stored in the character array

```//In single character units, select scanf/printf as the input / output function
# include <stdio.h>
void main()
{
char str={'a','b','c','d','e'};
int i;
for(i=0;i<sizeof(str)/sizeof(str);i++)
printf("%c",str[i]);
printf("\n");

}
```
```//If you store string data, you prefer to use gets and puts to implement the input-output function
# include <stdio.h>
void main()
{
char str[]="alan"；
puts(str);

```

### Common functions

(# include < string. H > header file)

```char str1={"People's Republic of "};
char str2[]={"China"};
printf("%s\n",strcat(str1,str2));//Strcat (character array 1, character array 2);
Display results:
People's Republic of China
Press any key to continue

```
```strlen Measuring string length, encountered'\0'end,'\0'Do not count
char str[]="alan";
printf("strlen(str)=%d\n",strlen(str));//Length without 0
printf("sizeof(str)=%d\n",sizeof(str));//The number of bytes of memory occupied by a variable
```
```	char str="welcome";
char str2[]="China";
strcpy(str,str2);
puts(str)
Display results
China
Press any key to continue
```
```
char str="abcdf";
char str2[]="abcde";
strcmp(str,str2);
printf("%d\n",strcmp(str,str2));
Display results
1

```

strlwr: converts uppercase letters to lowercase letters in a string
strupr: converts lowercase letters in a string to uppercase letters

## Program example of character array

```//Enter a line of string, count how many words there are, and separate the words with spaces
# include <stdio.h>
# include <string.h>

void main()
{
char string ;
int i,num=0,word=0;
char c;
gets(string);
for(i=0;(c=string[i])!='\0';i++)
{
if(string[i]== ' ')
{
word=0;
}
else if(word==0)
{
word=1;
num++;
}
}
printf("There are %d words in the line.\n",num);
}

```
```//Input the following characters from the keyboard: ******* A*BC**D ************************************************************
******A*BC**
# include<stdio.h>

void main()
{
char a;//******A*BC**D******
int i;
gets(a);
for(i=0;a[i]!='\0';i++);
i--;
while(a[i]=='*')
i--;
i++;
a[i]='\0';
puts(a);

}
```
```/*Input the following characters from the keyboard: ****** A*BC**D **********************************************************
******ABCD*******/
# include <stdio.h>
# include <string.h>

void main()
{
char a;
int i,j,k;
gets(a);
for(i=0;a[i]=='*';i++);
k=strlen(a)-1;
while(a[k]=='*')
k--;
for(j=i;j<=k;j++)
if(a[j]!='*')
{
a[i]=a[j];
i++;
}
for(j=k+1;a[j]!=0;j++,i++)
a[i]=a[j];
a[i]='\0';
puts(a);

}

```

# function

## Use reason and meaning of function

### Why do I need a function

```      Avoid repetitive operations
It is conducive to the modularization of the program
```

### What is a function

```     Logically: independent code blocks that can complete specific functions
Physically: it can receive data (of course, it can not accept data)
Be able to process the accepted data
The result of data processing can be returned (of course, no value can be returned)

Summary: function is a tool, which is designed to solve a large number of similar problems. The function can be a black box
```

## Definition of function

Type identifier function name (formal parameter table column)
{
Function executor
}
1. The essence of function definition is to describe in detail the specific method why a function can realize a specific function
2.return expression: 1 > terminate the called function and return the expression to the calling function
2> If the expression is empty, the function is terminated and no value is returned to the called function
3> Break is used to terminate loops and switch es, and return is used to terminate functions
3. The type of function return value is also called the type of function, because if the type before the function name is different, the type of final function return value shall be subject to the type of return value before the function name

```# include <stdio.h>

int print_fun(int m)//Called function, m is the formal parameter
{
printf("Hello World\n");
printf("Code:%d\n",m);
return 0;
}

void main()//calling function
{
int i = 1,vet;
vet = print_fun(i);//i is called the actual argument called by the calling function
printf("vet = %d\n",vet);
}

```

## Classification of functions

Parametric function nonparametric function
Function with return value function without return value
Library function user defined function
Normal function main function (main function)
A program must have and can only have one function
The main function can call ordinary functions
Ordinary functions cannot call the main function
Ordinary functions can call each other
The main function is the entry and exit of the program

## Problems needing attention

### The order in which functions are called and defined

If the function call is written before the function definition, the function pre declaration must be added
Function pre declaration: 1. Tell the compiler that several letters that may appear soon represent a function
2. Tell the compiler about the formal parameters and return values of the function represented by several letters that may appear soon
3. The function declaration is a statement, and a semicolon must be added at the end
4. The library function is declared by # including < file name where the library function is located. H >
The number of formal and actual parameters is the same; The locations correspond to each other one by one, and the data types must be compatible with each other
How to reasonably design functions in software development to solve practical problems
The function of a function is as independent and single as possible
Function is the basic unit of C language, and class is the basic unit of Java, c#, C + +

### Common system functions

```                     double sqrt(double x)     seek x Square root of
double fabs(double x)    seek x Absolute value of
int abs(int x)                   seek x Absolute value of
```

## Topic: function call

### Nested Call

```//Call three numbers, the difference between the maximum and minimum
# include <stdio.h>
# include <stdlib.h>

int max_(int x,int y,int z)
{
int t;
t = x > y? x : y;
return t > z? t : z;

}
int min_(int x,int y,int z)
{
int t;
t = x < y? x : y;
return t < z? t : z;

}
int dis(int x,int y,int z)
{
return max_(x,y,z) - min_(x,y,z);
}
void main()
{
int a,b,c,ret;
scanf("%d%d%d",&a,&b,&c);
ret=dis(a,b,c);
printf("ret=%d\n",ret);

}
```

### Recursive call

The direct or indirect call of a function itself
Known condition error condition progressive / delivery condition

```Fibonacci sequence
# include <stdio.h>
# include <math.h>

int fib(n)
{
if(n<=0)
return -1;
if(n==1||n==2)
return 1;
return (fib(n-1)+fib(n-2));
}
void main ()
{
int n;
scanf("%d",&n);
printf("%d\n",fib(n));
}
```
```Factorial n!
int fun(n)
{
if(n<0)
return -1;
if(n==0||n==1)
return 1;
return n * fun(n-1);
}
void main ()
{
int n;
scanf("%d",&n);
printf("%d\n",fun(n));
}
```

# Pointer

## First introduction to pointer usage

```#include <stdio.h>

void main()
{
int *p;//p is the name of the variable, and int *p means the address of the int type variable where the p variable is stored
int i = 3;
p = &i;//ok
//p=i;//error, because the types are inconsistent, P can only exist in the address of int type, and cannot exist in the value of int type
return 0;
}
```

1 int *p / / (1) does not mean that a variable named p is defined;
(2)p is the variable name, and the data type of p variable is int type (that is, the type that stores the address of int variable)
2.p = & i;// (1) . P saves the address of I, so p points to I
(2)p is not i, i is not p, more precisely: modifying the value of P does not affect the value of i, and modifying the value of i does not affect the value of P
(3) If a pointer variable points to an ordinary variable, the pointer is exactly the same as an ordinary variable
Example: if p is a pointer variable and p stores the address of ordinary i, p points to ordinary variable i
p is exactly equal to i
In other words, in all places where p appears, it can be replaced by i; in all places where i appears, it can be replaced by P
*p is a variable whose address is the content of p

### Key notes:

1. The pointer is the address, and the address is the pointer
2. Address is the number of memory unit
3. Pointer variable is the variable that stores the address
4. Pointer and pointer variable are two different concepts. However, it should be noted that pointer variables are usually called pointers when we describe them. In fact, they have different meanings

### Graphic description ## Classification of pointers

### Basic type pointer

```//Wild pointer: the pointer starts to use the space pointed to by the pointer before it has the space pointed to
#include <stdio.h>
void main()
{
int *p;
*p = 100;
printf("%d\n",*p);
}
```
```//NULL pointer: the pointer points to NULL
int *p=NULL;
```
```//Null type: it is legal to assign void * to any type of pointer, and it is also legal to assign any type of pointer to void *
void * temp;
temp= p;
q=temp;
```
```# include <stdio.h>
int main()
{
int i = 5;
int * p;
int * q;
p = &i;
i=123；
*p=456;
printf("%d\n",i);
printf("%d\n",*p);//i=456,*p=456
//*q = p;
//*q = *p;error syntax compilation will cause errors
p = q;//Q is the garbage value, q is assigned to p, and p becomes the garbage value
printf("%d\n",*q);//The space of Q belongs to the program, so the program can read and write the content of Q. however, if the internal value of Q is garbage, the program cannot read and write the content of * Q. at this time, the control authority of the memory unit represented by * q is not allocated to the program
}
```

Parameter transfer (value transfer is not appropriate, address transfer is appropriate)

```//pass by value
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
}
void main()
{
int i=3,j=5;
printf("i=%d,j=%d\n",i,j);
swap(i,j);
printf("i=%d,j=%d\n",i,j);
}
```
```//Address delivery
# include <stdio.h>
void huhuan_2(int *p, int *q)
{
int  t;//If you want to swap the values of p and q, t must be int
t = *p;
*p = *q;
*q = t;//p is int *, * p is int

}
void main()
{
int a = 3;
int b = 5;
huhuan_2(&a,&b);
//huhuan_2(* p,* q); wrong
printf("a = %d, b = %d\n",a,b);
}

```

Graphic description Note: * meaning 1. Multiplication
2. Define the pointer variable int *p / / define a variable named p. int indicates the address where only int variables can be stored
3. Pointer operator
This operator is placed on the defined pointer variable. If p is the defined pointer variable, p represents the variable with the content of p as the address

How to modify the value of the main calling function variable through the called function
1. The argument must be the address of the ordinary variable
2. The formal parameter must be a pointer variable
3. Pass in the called function
*Formal parameter name =
You can modify the values of the variables related to the main function

```//Example: enter three integers a, b and c and output them in size order
# include<stdio.h>
void main()
{
void exchange (int * q1,int * q2,int * q3);
int a, b, c,* p1,* p2,* p3;
scanf("%d,%d,%d",&a, &b, &c);
p1 = &a;
p2 = &b;
p3 = &c;
exchange(p1, p2, p3);
printf("\n%d,%d,%d\n",a,b,c);
}

void exchange (int * q1,int * q2,int * q3)
{
void swap(int * pt1, int * pt2);
if( * q1 < * q2)swap(q1,q2);
if(* q1 <  * q3)swap(q1,q3);
if(* q2 < * q3)swap(q2,q3);
}
void swap(int * pt1, int * pt2)
{
int temp;
temp = *pt1;
* pt1 = *pt2;
* pt2 = temp;
}
```

### Pointers and one-dimensional arrays

The one-dimensional array name is a pointer constant, which stores the address of the first element of the one-dimensional array
If P is a pointer variable, then p[i] is always equal to * (p+i)
Determining a one-dimensional array requires several parameters (the address of the first element of the array and the length of the array)

```//Basic pointers operate on one-dimensional arrays
# include <stdio.h>

void main()
{
int a[]={3,4,5,6,7,8,9,0};
int i;
int *p;
p=a;//p=&a;
for(i=0;i<sizeof(a)/sizeof(a);i++)
printf("%d ,*(p+i));
}
```
```//Pointer operation: when subtracting a pointer, two pointers often point to the same block of storage space, and the result is the number of elements that differ between the two pointers
# include <stdio.h>

void main()
{
int a[]={13,44,85,96,27,58,9,10};
int *p,*q;
p=&a;
q=&a;
printf("%d\n",q-p);
}

```
```//The input and output of one-dimensional array are controlled by pointer
# include <stdio.h>

void main()
{
int a;
int *p=a,i;
for(i=0;i<5;i++,p++)
scanf("%d",p);
p=a;//Reinitialize, because after the loop in the above, the pointer has pointed to the space outside the array
for(i=0;i<5;i++,p++)
printf("%d",*p);
printf("\n");
}

```

### Pointer and 2D array

```//Basic pointer operation two-dimensional array
# include <stdio.h>

void main()
{
int a={3,4,5,6,7,8};
int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d",*(*(p+i)+j));
printf("\n");
}
}

```

//Expand
int a;
int (p)=a; / / array pointer
Value: a[i][j]=((a+i)+j)=((p+i)+j) =p[i][j];
Address: & A [i] [J] = (a + I) + J = * (P + I) + J = & P [i] [J];

```//Pointer as function parameter, two-dimensional array
# include <stdio.h>

void print_arr(int(*p),int i,int j)
{
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d",*(*(p+i)+j));
printf("\n");
}
}

void main()
{
int a={3,4,5,6,7,8};
print_arr(a,2,3);
}

```
```//Exercise: build a two-dimensional array to store the scores of three students and four courses. Write functions to complete them respectively: (1) find the total average score, (2) output the specified students to view
# include <stdio.h>
# define M 3
# define N 4
float score_are(int *p, int n)
{
int i;
float sum = 0;
for(i=0;i<n;i++)
sum+=p[i];
return sum/n;
}
void find_stu(int(*p),int m, int n)
{
int id,i;
scanf ("%d",&id);
if(id<0||id>=m)
return;
for(i=0;i<n;i++)
printf("%d",*(*(p+id)+i));
printf("\n");
}
void main()
{
int a[M][N]={{89,87,91,76},{100,70,88,69},{95,89,71,80}};
printf("%f\n",score_are(*a,M*N));
find_stu(a,M,N);
}

```

### Pointer and character array

```# include <stdio.h>

void main()
{
char *p="Hello World";
char str[]="Hello World";
printf("sizeof(p)=%d\n",sizeof(p));
printf("sizeof(str)=%d\n",sizeof(str));
puts(p);
puts(str);//Same output
}
```

Function that returns address value (pointer function: function whose return value is address, such as int *fun(int,int))

```/*Use the function to find a row and return the address of the found relevant data*/
# include <stdio.h>

# define M 3
# define N 4

int* find_stu(int(*p),int m)
{
int id,i;
scanf ("%d",&id);
if(id<0||id>=m)
return NULL;
return *(p+id);
}
void main()
{
int a[M][N]={{89,87,91,76},{100,70,88,69},{95,89,71,80}};
int *p;
int i;
p=find_stu(a,M);
if (p==NULL)
printf("can not find!");
else
{
for(i=0;i<N;i++)
printf("%d",*(p+i));
}
}

```

### Pointer array (an array composed of pointers, that is, each member in the array is a pointer variable)

```# include <stdio.h>

void main()
{
int m=3,j=5,k=7,i;
int *arr={&m,&j,&k};
for(i=0;i<3;i++)
printf("%d",*arr[i]);
}
```

### Function pointer (pointer to function is called function pointer, int(*p)(int,int))

```# include <stdio.h>

{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int fun_op(int num1,int num2,int(*p)(int, int))
{
return p(num1,num2);
}

void main()
{
int i=3,j=5;