Two-dimensional array
Article directory
1. Application scenarios
For example, to develop a backgammon game, the board needs to be represented by a two-dimensional array
2. The use of two-dimensional arrays
快速入门案例:
请用二维数组输出如下图形
0 0 0 0 0 0
0 0 1 0 0 0
0 2 0 3 0 0
0 0 0 0 0 0
Usage 1:
语法: 类型 数组名[大小][大小];
2) 比如: int a[2][3];
3) 使用演示
4) 二维数组在内存的存在形式,各个元素的地址是连续分布的,即在
前一个元素基础上+4
Usage 2:
定义 类型 数组名[大小][大小] = {
{值1,值2..},{值1,值2..},{值1,值2..}};
或者 类型 数组名[大小][大小] = { 值1,值2,值3,值4,值5,值6 ..};
3. Traversal of two-dimensional arrays
Case 1:
Please use a flexible way to traverse the following arrays:
int map[3][3] = { {0,0,1},{1,1,1},{1,1,3}};
Case 2:
int arr[3][2]={ {4,6},{1,4},{-2,8}};
Traverse the two-dimensional array and get the sum?
Case 3:
Define a two-dimensional array to save the results of three classes and five students in each class.
And find the average score of each class, and the average score of all classes
#include <stdio.h>
int main(){
//定义二维数组,用于保存三个班,每个班五名同学成绩,
//并求出每个班级平均分、以及所有班级平均分【 数据要求从控制台输入 】
//1.创建一个score[3][5]
double score[3][5];
//int rows =3,cols=5,i,j;
//更灵活的处理方式
int rows, cols, i, j;
rows = sizeof(score) / sizeof(score[0]);
cols = sizeof(score[0])/sizeof(double);
double totalScore = 0.0,classTotalScore = 0.0;
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
score[i][j]=0.0;//赋0.0,初始化
}
}
//2.遍历,给每个学生输入成绩
for (i = 0; i < rows; i++ ) {
for (j = 0; j < cols ; j++ ) {
printf("请输入第 %d 个班的 第 %d 个 学生的成绩", i + 1, j + 1);
scanf("%lf", &score[i][j]);
}
}
//getchar();
//3.显示下成绩情况
for (i = 0; i < rows; i++ ) {
for (j = 0; j < cols ; j++ ) {
printf("%.2f ",score[i][j]);
}
printf("\n");
}
//4.统计各个班的总成绩,和所有学生的总成绩
for (i = 0; i < rows; i++ ) {
classTotalScore = 0.0; // 每次清0
for (j = 0; j < cols ; j++ ) {
classTotalScore += score[i][j]; //累计每个班的总成绩
}
printf("\n第 %d 个班的平均成绩是 %.2f" , i+1, classTotalScore/cols );
totalScore += classTotalScore; //将该班级的总分,累计到 totalScore
}
printf("\n所有学生总成绩是 %.2f 平均成绩 %.2f" , totalScore, totalScore/(rows * cols));
getchar();
getchar();
}
4. Two-dimensional array experiment details and precautions
(1) You can only assign values to some elements, and the unassigned elements automatically take the "zero" value
(2) If all elements are assigned, the length of the first dimension may not be given.
int a[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
可以写为:
int a[][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
(3) A two-dimensional array can be regarded as a nested one-dimensional array; if each element of an array is an
array, then it is a two-dimensional array.
二维数组a[3][4]可看成三个一维数组,它们的数组名分别a[0],a[1],a[2]。
这三个一维数组都有 4 个元素,如,一维数组 a[0] 的元素为 a[0][0]、a[0][1]、a[0][2]、a[0][3]