二维数组的四种定义方式:
* 1、数组类型 数组名 [行数][列数];
* 2、数组类型 数组名 [行数][列数]={{数据1,数据2},{数据3,数据4}};
* 3、数组类型 数组名 [行数][列数]={数据1,数据2,数据3,数据4};
* 4、数组类型 数组名 [ ][列数]={数据1,数据2,数据3,数据4};
第二种定义方式更加直观,提高代码的可读性。
#include<iostream>
using namespace std;
int main()
{
/*二维数组:在一维数组上多加一个维度
* 二维数组的4种定义方式:
* 1、数组类型 数组名 [行数][列数];
* 2、数组类型 数组名 [行数][列数]={{数据1,数据2},{数据3,数据4}}; 此种定义方式更加直观,提高代码的可读性
* 3、数组类型 数组名 [行数][列数]={数据1,数据2,数据3,数据4};
* 4、数组类型 数组名 [ ][列数]={数据1,数据2,数据3,数据4};
*/
int arr1[2][2];
arr1[0][0] = 101; arr1[0][1] = 102; arr1[1][0] = 103; arr1[1][1] = 104;
cout << "二维数组的第一种定义方式:int arr1[2][2]" << endl;
cout << endl;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout << endl;
int arr2[3][3] = { {1,2,3},{4,5,6} };
cout << "二维数组的第二种定义方式:int arr2[3][3] = { {1,2,3},{4,5,6} }" << endl;
cout << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr2[i][j] << " ";
}
cout << endl;
}
cout << endl;
int arr3[2][5] = { 1,2,3,4,5,6,7,8,9,0 };
cout << "二维数组的第三种定义方式:int arr3[2][5] = { 1,2,3,4,5,6,7,8,9,0 }" << endl;
cout << endl;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
cout << arr3[i][j] << " ";
}
cout << endl;
}
cout << endl;
int arr4[][3] = { 11,22,33,44,55,66,77,88,99 };
cout << "二维数组的第四种定义方式:int arr[][3] = { 11,22,33,44,55,66,77,88,99 }" << endl;
cout << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr4[i][j] << " ";
}
cout << endl;
}
cout << endl;
system("pause");
return 0;
}
二维数组数组名的用途
#include<iostream>
using namespace std;
int main()
{
/*二维数组的数组名的用途
* 1、统计占用内存空间的大小
* 2、查看二维数组的首地址
*/
int arr[3][2] = { 1,2,3,4,5,6 };
cout << "二维数组为:" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
cout << arr[i][j]<<" ";
}
cout << endl;
}
cout << endl;
cout << "二维数组占用的内存空间为:" << sizeof(arr) << endl << endl;
cout << "二维数组第一行占用的内存空间为:" << sizeof(arr[0]) << endl << endl;
cout << "二维数组第一个元素占用的内存空间为:" << sizeof(arr[0][0]) << endl << endl;
cout << "二维数组的行数为:" << sizeof(arr) / sizeof(arr[0]) << endl << endl;
cout << "二维数组的列数为:" << sizeof(arr[0]) / sizeof(arr[0][0]) << endl << endl;
cout << "二维数组的首地址(十六进制)为:" << arr << endl << endl;
cout << "二维数组的首地址(十进制)为:" << (int)arr << endl << endl;
//cout << "二维数组的首地址(十进制)为:" << (int)arr[0][0] << endl << endl;
system("pause");
return 0;
}
二维数组应用案例
#include<iostream>
using namespace std;
int main()
{
/*二维数组应用案例
* 输出3名同学的总成绩
* 输出3门课程的平均成绩
*/
int arr[3][3] = { {100,100,100},{90,50,100},{60,70,80} };
int score = 0;
for (int i = 0; i < 3; i++)
{
int score = 0;
cout << "第" << i+1 << "名同学的总成绩为:";
for (int j = 0; j < 3; j++)
{
score = score + arr[i][j];
}
cout << score << endl;
}
cout << endl;
for (int i = 0; i < 3; i++)
{
int score = 0;
cout << "第" << i+1 << "门课的平均成绩为:";
for (int j = 0; j < 3; j++)
{
score = score + arr[j][i];
}
cout << score/3 << endl;
}
cout << endl;
system("pause");
return 0;
}