C++编程基础一 27-二维数组

 1 // 27-二维数组.cpp: 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <climits>
 7 #include <array>
 8 #include <string>
 9 using namespace std;
10 
11 int main()
12 {
13     int scores[5] = { 34,6,34,835,3 }; //一维数组
14     int scores2[4][5] = {   //可以理解为长度为4的数组,每个数组中又包含了长度为5的数组,数组中包含数组。
15                             //类似树状图,分为上下两层。第一层是第一维,从第一层中分支出第二层,第二维。
16         {123,235,4,62,321},
17         {73,132,6,833,452},
18         {3426,78,421,3,6742},
19         {34,6,9,13,6},
20     };
21 
22     //如何访问二维数组?
23     cout << scores2[1][1] << endl; //访问第二行第二列数组。132
24     //如何遍历二维数组呢?有两个索引。使用循环嵌套。
25     for (int i = 0; i < 5; i++)
26     {
27         for (int j = 0; j < 6; j++)
28         {
29             cout << "i:" << i <<"  "<< "j" << j << endl;
30         }
31     }
32 
33     //方式1,先遍历行(一层),后遍历列(二层)。
34     for (int i = 0; i < 4; i++)
35     {
36         for (int j = 0; j < 5; j++)
37         {
38             cout << scores2[i][j] << " ";
39         }
40         cout << endl;
41     }
42 
43     //方式2,先遍历列(二层),后遍历行(一层)。
44     for (int i = 0; i < 5; i++) //i代表第二层的位置
45     {
46         for (int j=0;j<4;j++) //j代表第一层的位置
47         {
48             cout << scores2[j][i] << " ";
49         }
50         cout << endl;
51     }
52 
53     int t;
54     cin >> t;
55     return 0;
56 }

 

posted on 2018-07-21 14:21  uimodel  阅读(154)  评论(0编辑  收藏  举报

导航