1、二维数组
在一维数组上多加了一个维度。
1.1定义方式
二维数组定义的四种方式:
1.数据类型 数组名 [行数] [列数];
2.数据类型 数组名 [行数] [列数] = {{数据1,数据2 },{数据3,数据4 } };
3.数据类型 数组名 [行数] [列数] = {数据1,数据2,数据3,数据4};
4.数据类型 数组名 [ ] [列数] = {数据1,数据2,数据3,数据4};
一般使用第二种。
例:arr[2] [3]
#include<iostream>
using namespace std;
int main()
{
//二维数组定义方式
/*
1.数据类型 数组名 [行数] [列数];
2.数据类型 数组名 [行数] [列数] = {{数据1,数据2 },{数据3,数据4 } };
3.数据类型 数组名 [行数] [列数] = {数据1,数据2,数据3,数据4};
4.数据类型 数组名 [ ] [列数] = {数据1,数据2,数据3,数据4};
*/
//1.数据类型 数组名[行数][列数];
int arr[2][3];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
cout << arr[0][0] << endl;
cout << arr[0][1] << endl;
cout << arr[0][2] << endl;
cout << arr[1][0] << endl;
cout << arr[1][1] << endl;
cout << arr[1][2] << endl;
//外层循环打印行数,内层循环打印列数
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
//2.数据类型 数组名 [行数] [列数] = {{数据1,数据2 },{数据3,数据4 } };
int arr2[2][3] =
{
{11,12,13},
{14,15,16}
};
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr2[i][j] << " ";
}
cout << endl;
}
//3.数据类型 数组名[行数][列数] = { 数据1,数据2,数据3,数据4 };
int arr3[2][3] = { 21,22,23,24,25,26 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr3[i][j] << " ";
}
cout << endl;
}
//4.数据类型 数组名 [ ] [列数] = {数据1,数据2,数据3,数据4};
int arr4[][3] = { 31,42,43,44,45,46 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr4[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
1.2二维数组数组名
查看二维数组所占内存空间
获取二维数组首地址
#include<iostream>
using namespace std;
int main()
{
//二维数组组名用途
//1、查看占用内存空间大小
int arr[2][3] =
{
{1,2,3,},
{4,5,6}
};
cout << "二维数组占用空间" << sizeof(arr) << endl;
cout << "第一行占用空间" << sizeof(arr[0]) << endl;
cout << "第一个元素占用空间" << sizeof(arr[0][0]) << endl;
cout << "二维数组行数" << sizeof(arr) / sizeof(arr[0]) << endl;
cout << "二维数组列数" << sizeof(arr[0]) / sizeof(arr[0]) << endl;
//2、产看二维数组的首地址
cout << "二维数组首地址" << (int)arr << endl;
cout << "二维数组第一行首地址" << (int)arr[0] << endl;
cout << "二维数组第一个元素首地址" << (int)arr[0][0] << endl;
system("pause");
return 0;
}
二维数组应用案例
1、创建二维数组,3行3列
2、统计考试成绩,让每行的3列相加,统计出总和
#include<iostream>
using namespace std;
int main()
{
//考试成绩统计
//1、创建二维数组,3行3列
int fenshu[3][3] =
{
{100,100,100},
{90,50,100},
{60,70,80}
};
string names[3] = { "张三","李四","王五" };
//2、统计考试成绩,让每行的3列相加,统计出总和
for (int i = 0; i < 3; i++)
{
int sum = 0;
for (int j = 0; j < 3; j++)
{
sum += fenshu[i][j];
cout << fenshu[i][j] << " ";
}
//cout << "第"<<i + 1<<"个人分数为:"<<sum<<endl;
cout<<names[i] << "分数为:" << sum << endl;
}
system("pause");
return 0;
}