array ：
1 Introduction of array and basic syntax

1） Some problems need us to keep a lot of data .
case ： There are in the class 10 Students , Adjust students' grades according to their average scores , If the average score is less than 55 branch , Then each student improves 10 branch .
#include <stdio.h> int main() { int score[10] = {60,70,30,50,56,56,60,70,30,50}
; // Find out the average score of the students int i; int sum = 0; for(i=0; i<10; ++i) { sum += score[i]; }
// Average score int m = sum/10; printf("%d\n", m); if(m<55) { // Each student's performance improved 10 branch for(i=0; i
<10; ++i) { score[i] += 10; } } // Output each element in the array for(i=0; i<10; ++i){ printf("%3d",
score[i]); } return 0; }
for(i=0; i<10; ++i) { 　　scanf("%d", &score[i]); }
2） Array definition syntax
Arrays are used to store a series of data , But it is often thought of as a series of variables of the same type .
The storage position of array elements in memory is continuous .

3） Initialization of array elements
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; double balance[] = {1000.0,
2.0, 3.4, 7.0, 50.0};
4） Use of array elements

Access and modification
Array elements can be accessed through the array name and index . The index of the element is placed in square brackets , Following the array name .
You can read or modify the values of elements in an array .
The position subscript is from 0 Starting . The subscript of the last element is N-1( Suppose the array capacity is N Elements )

Pay attention to the subscript when accessing the element .
int score[10] = {60,70,30,50,56,56,60,70,30,50}; score[0];
5） Gets the size of the array （ Number of bytes ）, Gets the number of elements in the array

2 Typical cases of using arrays

1） Store a large amount of data and complete the algorithm for a large amount of data , The most fundamental question , The algorithm is simple （ It can be done without arrays , But you can't keep all the data ）
Find the maximum or minimum of these data .
#include <stdio.h> int main() { int a[5] = {2,3,7,5,1}; int m = a[0]; for(int i
=1; i<5; i++){ if(a[i]>m){ m = a[i]; } } printf("max is %d\n", m); return 0; }
extend ： While looking for the maximum value , The position number where the maximum value is to be given .
#include <stdio.h> int main() { int a[5] = {2,3,7,5,1}; int m = a[0]; int pos =
0; for(int i=1; i<5; i++){ if(a[i]>m){ m = a[i]; pos = i; } } printf("max is %d
at %d\n", m, pos); return 0; }
Look for a number in the data （ Or a number that meets certain conditions ）, Find the position of the returned number in the sequence , No return found -1.
#include <stdio.h> int main() { int a[5] = {2,3,7,5,1}; int n = 3; int pos = -1
; for(int i=0; i<5; i++){ if(a[i]==n){ pos = i; break; } } if(pos==-1) printf(
"not find"); else{ printf("find at %d", pos); } return 0; }
2） Save statistical results with array . Example ： Enter an integer （ It could be very long ）, Count the number of times each number appears in an integer .
as input 1124511, output 0：0, 1：4,2：1,3：0,4：1,5：1,6：0,7：0,8：0,9：0
Use an array to hold the number of numbers ,a[0] preservation 0 Number of ,a[9] preservation 9 Number of ,int a[10]
Gets each digit of the input integer , After the corresponding array of statistical elements to add an operation .

How to get every bit of an integer ?（ Integer separation , You can use a loop ）
How to deal with long integers ?（ So you can't use integer variables ）
#include <stdio.h> int main() { char c; int a[10] = {0}; c = getchar(); //
c='1' // Complete the statistics of the number of figures at the same time of input while(c!='\n'){ a[c-'0']++; // '1' - '0' c = getchar();
} // Print and input statistical results according to the requirements of the title （ Statistical array ） for(int i=0; i<10; i++){ printf("%d:%d\n", i, a[i]); }
return 0; }
extend 1, Enter a string of letters , Count the number of times each letter appears .（ Yes 26 An array of elements to store the number of letter occurrences , You may also consider case letters , Letter corresponding subscript c-‘a’）

extend 2, Enter a string of letters and numbers , Count the number of times each number and letter appears .( Multiple arrays , Some store the number of arrays , Some store the number of letters )

extend 3, Input letters , number , A string of spaces and other characters , Statistical letters （ The total number of letters ）, number （ Total number of figures ）, The number of spaces and other characters .（ You don't need arrays ）

3） Store a series of numbers , Auxiliary completion iterative algorithm . The array version of fibolacci sequence .
#include <stdio.h> int main() { int a[10] = {0}; a[0] = 1; a[1] = 1; for(int i=
2; i<10; i++){ a[i] = a[i-1] + a[i-2]; printf("%d ", a[i]); } return 0; }
4） Store a lot of data , Complete the algorithm for a large number of data , Advanced problems and algorithms .
Select sort
#include <stdio.h> int main() { const int n = 5; int a[5] = {3, 2, 4, 5, 1};
for(int i=0; i<n-1; i++){ // stay a[i] reach a[n-1] Find and record the location of the smallest value in the range , And placed in the i Location ( and a[i] exchange ) int
m= a[i], k; int j; for(j=i+1, k=i; j<n; j++){ if(a[j]<m){ m = a[j]; k = j; } }
// exchange a[k] and a[i] int t = a[i]; a[i] = a[k]; a[k] = t; } // Output array for(int i=0; i<
n; i++){ printf("%4d", a[i]); } return 0; }
extend ,1） From big to small . 2） Student number array and grade array , One to one correspondence . Output the student number in ascending order （ full name ）.（ Sort by score array , At the same time, exchange the corresponding student number ）
Bubble sort
#include <stdio.h> int main() { const int n = 5; int a[5] = {3, 2, 4, 5, 1};
for(int i=0; i<n-1; i++){ for(int j=0; j<n-1-i ;j++){ // Pairwise comparison , If greater than, exchange if(a[j]>a[j+
1]){ int t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } // Output array for(int i=0; i<n; i
++){ printf("%4d", a[i]); } return 0; }
Insert sort
Merge sort

lookup
Violence search
Binary search （ More efficient , But the elements in the array are required to be ordered ）
#include <stdio.h> int main() { const int n = 5; int a[5] = {1, 2, 3, 4, 5};
int s=0, e=n-1; int x = 8; int pos = -1; while(s<=e){ int mid = (s+e)/2; if(a[
mid]==x){ pos = mid; break; }else if(x>a[mid]){ s = mid+1; }else if(x<a[mid]){ e
= mid-1; } } if(pos==-1){ printf("not find\n"); }else{ printf("found %d at %d\n"
, x, pos); } return 0; }
5） Use array to store fixed data , Directly extract and use in the code , Avoid tedious and repeated calculation .

Calculate the number of days in a month of a year ?
You can advance the days of a month into an array of days , The month is then used as the subscript of the array , Take it directly from the array , It makes the logic and implementation of the code very simple .
give an example , What day of the year is the calculation date ?
#include <stdio.h> int is_leap(int y) { return ((y%4==0&&y%100!=0) || y%400==0)
; } int main() { int a[13] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273,
304, 334}; // How many days are there in the year before each month int y = 2000; int m = 3; int res = a[m]; if (m>=3 &&
is_leap(y)) res += 1; printf("%d\n", res); return 0; }
6） A lot of data must be saved first , Then the subsequent processing can be carried out .
Introductory cases （ See the example above ）
Integer factorization , Each digit is output in positive sequence . Detailed explanation and reference MOOC B.
Is there any other better solution ?（ Using arrays ）
Get each number in reverse order , Put them in the array , Reverse output array .
#include <stdio.h> #include <math.h> int main() { int a=187; int num[100]; int
i=0; int d; do{ d = a%10; num[i] = d; i++; a /= 10; }while(a>0); for(int j=i-1;
j>=0; j--){ printf("%4d", num[j]); } return 0; }
Example ： This question requires calculation /, among A No more than 1000 Bit positive integer ,B yes 1 Bit positive integer . You need to export quotient Q Sum remainder R, bring A=B×Q+R establish .
Input format ：
The inputs are given in turn on a line A and B, In the middle 1 Space separation .
Output format ：
Output in sequence on a line Q and R, In the middle 1 Space separation .
sample input ：
123456789050987654321 7
sample output ：
17636684150141093474 3
#include <stdio.h> int main() { int a[1001] = {0}; char c; int i = 0; while((c=
getchar())!=' ') { a[i++] = c-'0'; } int b; scanf("%d", &b); int yu = 0; for(int
j=0; j<i; j++) { int tem = yu*10+a[j]; a[j] = tem/b; yu = tem%b; } int b_first
= 1; for(int j=0; j<i; j++) { if(b_first){ if(a[j]!=0){ printf("%d", a[j]);
b_first= 0; } } else printf("%d", a[j]); } if(b_first) printf("0"); printf(" %d"
, yu); return 0; }
Two dimensional array
1 The meaning and basic syntax of two dimensional array
1） significance
There are two dimensions , It can be thought of as a row and column structure . Imagine an image of a two-dimensional structure .
2） Definition and initialization
int x[3][4]; int a[3][4] = { {0, 1, 2, 3} , /* Initialize index number to 0 The line of */ {4, 5, 6, 7} ,
/* Initialize index number to 1 The line of */ {8, 9, 10, 11} /* Initialize index number to 2 The line of */ }; int a[3][4] = {0,1,2,3,4
,5,6,7,8,9,10,11};
A continuous array of elements in a two-dimensional memory , It is expanded into a one-dimensional structure in the order of rows .

3） Reference and access modification
a[1][2]
Each element is usually accessed in combination with a double loop .

2 Typical application of two dimensional array

1） Store 2D structure data , Statistical analysis of two-dimensional data
Make a score sheet , Many students , I have studied many subjects .
Two dimensional table , Score sheet , A line represents a classmate , A column represents a subject .
Total and average of all grades . Average score per subject . Average score of each student .

2） Simulate operations on Matrices
Matrix transposition
Topic content ：
Using two dimensional array as function parameter , Program calculation and output n×n Transpose matrix of order matrix . among ,n The value of does not exceed 10,n The value of is entered by the user from the keyboard .
Example of program running results 1：
Input n:3↙
Input 33 matrix:
1 2 3↙
4 5 6↙
7 8 9↙
The transposed matrix is:
1 4 7
2 5 8
3 6 9
Example of program running results 2：
Input n:2↙
Input 22 matrix:
1 2↙
4 5↙
The transposed matrix is:
1 4
2 5
#include <stdio.h> int main() { int a[10][10]; printf("Input n:"); int n; scanf
("%d", &n); printf("Input %d*%d matrix:\n", n, n); for(int i=0; i<n; i++){ for(
int j=0; j<n; j++){ scanf("%d", &a[i][j]); } } for(int i=0; i<n; i++){ for(int j
=0; j<i; j++){ int t = a[i][j]; a[i][j] = a[j][i]; a[j][i] = t; } } printf("The
transposed matrix is:\n"); for(int i=0; i<n; i++){ for(int j=0; j<n; j++){
printf("%4d", a[i][j]); } printf("\n"); } return 0; }
Check and print magic square matrix
Topic content ：

Magic square matrix refers to each row in the matrix , Each column , The sum of the elements on each diagonal is equal . Enter one from the keyboard 5×5 And store it in a two-dimensional integer array , Check whether it is magic square matrix , And display it on the screen in the specified format .
Input format : “%d”
Output format ：
If it's a magic square matrix , Output prompt information : “It is a magic square!\n”
Output of matrix elements ： “%4d”（ Line feed "\n"）
If not magic square matrix , Output prompt information : “It is not a magic square!\n”
sample input 1：
17_24_1_8_15
23_5_7_14_16
4_6_13_20_22
10_12_19_21_3
11_18_25_2_9
( Input into the sample “” Represents the space )
sample output 1：
It is a magic square!
17241815
23571416
46132022
10121921*3
111825***2**9
( In the output sample “” Represents the space )
sample input 2：
1_0_1_6_1
3_1_1_1_1
1_1_1_1_2
1_1_1_1_1
9_1_7_1_1
( Input into the sample “” Represents the space )
sample output 2：
It is not a magic square!
First find the sum of all the elements in the first row of the matrix , Put in sum in , Then find the sum of other rows or columns or diagonals , The other sum is equal to sum, The explanation is , Otherwise it is not .
#include <stdio.h> #include <math.h> int main() { int a[5][5]; int n = 5; int i
, j; for(i=0; i<5; i++){ for(j=0; j<5; j++){ scanf("%d", &a[i][j]); } } int flag
= 1; int s = 0; for(i=0; i<n; i++){ s += a[i][0]; } int s1 = 0; for(i=0; i<n; i
++){ s1 += a[i][n-1]; } if(s1!=s) flag = 0; s1 = 0; for(j=0; j<n; j++) s1 += a[0
][j]; if(s1!=s) flag = 0; s1 = 0; for(j=0; j<n; j++) s1 += a[n-1][j]; if(s1!=s)
flag= 0; s1 = 0; for(i=0; i<5; i++){ s1 += a[i][i]; // Elements on the diagonal } if(s1!=s) flag
= 0; s1 = 0; for(i=0; i<5; i++){ s1 += a[i][n-1-i]; // Elements on the anti diagonal } if(s1!=s) flag
= 0; if(flag==1){ printf("It is a magic square!\n"); for(i=0; i<5; i++){ for(j=0
; j<5; j++){ printf("%4d", a[i][j]); } printf("\n"); } } else{ printf("It is
not a magic square!\n"); } return 0; }
#include<stdio.h> int main(void) { int a[10][10]; int m, n; scanf("%d%d", &m, &
n); for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ scanf("%d", &a[i][j]); } }
// Store the maximum value of each row and the minimum value of each column in advance int maxs[10] = {0}; for(int i=0; i<m; i++){ maxs[i] = a[i
][0]; for(int j=1; j<n; j++){ if(a[i][j]>maxs[i]){ maxs[i] = a[i][j]; } } } int
mins[10] = {0}; for(int j=0; j<n; j++){ mins[j] = a[0][j]; for(int i=1; i<m; i++
){ if(a[i][j]<mins[j]){ mins[j] = a[i][j]; } } } int flag = 0; for(int i=0; i<m;
i++){ for(int j=0; j<n; j++){ if(a[i][j]==maxs[i] && a[i][j]==mins[j]){ printf(
"Array[%d][%d]=%d\n", i, j, a[i][j]); flag = 1; } } } if(!flag){ printf("None\n"
); } return 0; }
Serpentine matrix filling
#include <stdio.h> int a[101][101]; void print(int a[][101], int n) { for(int i
=0; i<n; i++){ for(int j=0; j<n; j++){ printf("%4d", a[i][j]); } printf("\n"); }
} /* Fill in diagonal order , The direction of filling is controlled by using the parity of the number of diagonal lines , Plan each diagonal in advance Number of fills , Processing at the boundary */ int main() {
int n; printf("Input n:\n"); int n_in = scanf("%d", &n); if(n_in!=1 || n>100 ||
n<=0){ printf("Input error!\n"); return 0; } int N = n*n; int line_no = 1,
num_in_line= 1; int m = 1; int i=0, j=0; while(m<=N){ // fill a line for(int k=0
; k<num_in_line; k++){ a[i][j] = m++; if(line_no%2==1){ if(i-1>=0 && j+1<=n-1) i
--, j++; } else{ if(i+1<=n-1 && j-1>=0) i++, j--; } } // end of line // locate
i, j for next line if(line_no<n){ if(line_no%2==1 && j<n-1) j+=1; if(line_no%2==
0 && i<n-1) i+=1; num_in_line++; } else{ if(line_no%2==1 && j==n-1) i+=1; if(
line_no%2==0 && i==n-1) j+=1; num_in_line--; } line_no++; } print(a, n); return
0; } #include <stdio.h> int a[101][101]; void print(int a[][101], int n){ for(
int i=0; i<n; i++){ for(int j=0; j<n; j++){ printf("%4d", a[i][j]); } printf(
"\n"); } } /* from 1 Start filling i_sign = -1, j_sign = +1; Boundary and boundary change j==n-1 --> i+=1; i==n-1
--> j+=1; i==0--> j+=1; j==0 --> i+=1; Change direction at the boundary at the same time i_sign *= -1; j_sign *= -1;
The boundary is filled with the next position at the same time （ Starting point of new slash ） a[i][j]=m++; Move position in all cases i += i_sign; j += j_sign;
Note that at the boundary, the next position should be filled and then skipped , The next position at the boundary should not be used as a boundary */ int main() { int n; printf(
"Input n:\n"); int n_in = scanf("%d", &n); if(n_in!=1 || n>100 || n<=0){ printf(
"Input error!\n"); return 0; } int N = n*n; //int line_no = 1, num_in_line = 1;
int m = 1; //a[0][0] = m++; int i=0, j=0, i_sign=-1, j_sign=1; while(m<=N){ a[i]
[j] = m++; if(j==n-1){ i+=1; a[i][j]=m++; i_sign *= -1; j_sign *= -1; }else if(i
==n-1){ j+=1; a[i][j]=m++; i_sign *= -1; j_sign *= -1; }else if(i==0){ j+=1; a[i
][j]=m++; i_sign *= -1; j_sign *= -1; }else if(j==0){ i+=1; a[i][j]=m++; i_sign
*= -1; j_sign *= -1; } i += i_sign; j += j_sign; } print(a, n); return 0; } #
include <stdio.h> int a[101][101]; void print(int a[][101], int n){ for(int i=0;
i<n; i++){ for(int j=0; j<n; j++){ printf("%4d", a[i][j]); } printf("\n"); } }
/* from 1 Start filling i_sign = -1, j_sign = +1; Boundary and boundary change j==n-1 --> i+=1; i==n-1 --> j+=1;
i==0--> j+=1; j==0 --> i+=1; Change direction at the boundary at the same time The boundary is filled with the next position at the same time （ Starting point of new slash ） a[i][j]=m++;
Move position in all cases i += i_sign; j += j_sign;
Note that at the boundary, the next position should be filled and then skipped , The next position at the boundary should not be used as a boundary */ int can_step(int i, int j, int
i_sign, int j_sign, int n){ i+=i_sign; j+=j_sign; if(i<0||i>n-1||j<0||j>n-1)
return 0; else return 1; } int main() { int n; printf("Input n:\n"); int n_in =
scanf("%d", &n); if(n_in!=1 || n>100 || n<=0){ printf("Input error!\n"); return
0; } int N = n*n; int m = 1; int i=0, j=0, i_sign=-1, j_sign=1; while(m<=N){ a[i
][j] = m++; if(!can_step(i,j,i_sign,j_sign,n)){ if(j==n-1){ i+=1; }else if(i==n-
1){ j+=1; }else if(i==0){ j+=1; }else if(j==0){ i+=1; } i_sign *= -1; j_sign *=
-1; }else{ i += i_sign; j += j_sign; } } print(a, n); return 0; }
Yanghui triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
#include<stdio.h> int main(void) { int a[10][10]; for(int i=0; i<10; i++){ a[i]
[0] = 1; a[i][i] = 1; } for(int i=2; i<10; i++){ for(int j=1; j<i; j++){ a[i][j]
= a[i-1][j] + a[i-1][j-1]; } } for(int i=0; i<10; i++){ for(int j=0; j<=i; j++){
if(j==0) printf("%d", a[i][j]); else printf(" %d", a[i][j]); } printf("\n"); }
return 0; }

Technology
Daily Recommendation
views 4
views 3