C++中的二维数组

目录

C++中的二维数组

一、二维数组的定义

二、二维数组的数组名

三、二维数组案例——考试成绩统计


C++中的二维数组

一、二维数组的定义

1、数据类型  数组名[ 行数 ][ 列数 ];

//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] << endl;
		}
	}

2、数据类型  数组名[ 行数 ][ 列数 ] = {{数据1,数据2},{数据3,数据4}};

//2、数据类型  数组名[ 行数 ][ 列数 ] = {{数据1,数据2},{数据3,数据4}};

	int arr2[2][3] =
	{
		{1,2,3},
	    {4,5,6}
	};
	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};

	3、数据类型  数组名[ 行数 ][ 列数 ] = {数据1,数据2,数据3,数据4};
	int arr3[2][3] = { 1,2,3,4,5,6 };
	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] = { 1,2,3,4,5,6 };
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			cout << arr4[i][j] << " ";
		}
		cout << endl;
	}

二、二维数组的数组名

1、可以查看占用内存空间大小;

#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][0]) << endl;


	system("pause");
	return 0;
}

2、可以查看二维数组的首地址。

#include<iostream>
using namespace std;

int main()
{
	//二维数组名称用途

	//2、可以查看二维数组的首地址
	cout << "二维数组的首地址为:" << (int)arr << endl;
	cout << "二维数组第一行首地址为:" << (int)arr[0] << endl;
	cout << "二维数组第一行首地址为:" << (int)arr[1] << endl;

	cout << "二维数组第一个元素首地址为:" << (int)&arr[0][0] << endl;
	cout << "二维数组第一个元素首地址为:" << (int)&arr[0][1] << endl;


	system("pause");
	return 0;
}

三、二维数组案例——考试成绩统计

#include<iostream>
using namespace std;
#include<string>

int main()
{
	//二维数组案例-考试成绩统计

	//1、创建二维数组
	int scores[3][3] =
	{
		{100,100,100},
		{90,50,100},
		{60,70,80}
	};

	string name[3] = { "张三","李四","王五" };

	//2、统计每个人的总分数
	for (int i = 0; i < 3; i++)
	{
		int sum = 0;
		for (int j = 0; j < 3; j++)
		{
            sum += scores[i][j];
			cout << scores[i][j] << " ";

		}
		cout <<name[i]<<"的总分为" <<sum << endl;
	}


	system("pause");
	return 0;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值