# 陣列 (Array)
###### tags: `程式設計` `陣列`
如果你是一位老師,你想要用C++來計算班上每位同學分數的平均,你可能需要宣告很多變數。
| 成績編號 | 1 | 2 | 3 |4 |5 |6 |7 |
|:--------:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|
| 王大明 | 82 | 65 | 99|88| 84| 76| ...|
|柳橙之 | 50 | 54 | 55|68| 55| 55|...|
|...|score1|score2|score3|score4|score5|..|
int score1, score2, score3, score4, score5, ... ;
這樣會沒完沒了
幸好程式設計師發明了能方便儲存多筆資料的 **陣列**,陣列能夠把很多筆資料都儲存在一個地方。
```cpp
int score1, score2, score3, score4, score5, ...;
```
:arrow_down:
```cpp
int score[100];
```
宣告陣列的方式,首先是資料型態,然後陣列名稱,再來是資料數量
---
如果資料的種類很多,也可以使用不同維度的陣列。
<font size = 5>**<一維陣列>**</font>
| 編號 | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
| ---- |:----:|:----:|:----:|:----:|:----:|:----:|:----:|
| 資料 | 82 | 65 |99 |88 |84|76|...|
```cpp
int score[6] ={ 82, 65, 99, 88, 84, 76}
```
<font size = 5>**<二維陣列>**</font>
| 列/行 | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|:----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| 0 | 82 | 65 | 99 | 88 | 84 | 76 | ... |
| 1 | 100 | 85 | 88 | 90 | 99 | 85 | ... |
| 2 | ... | ... | ... | ... |... | ... | ... |
```cpp
int score[2][6]={
{82,65,99,88,84,76},
{100,85,88,90,99,85}
}
```
score[2][6] 中 2稱為 **列數**,6稱為 **行數**,宣告的時候要先宣告列再來才是行
由於已經有宣告列數和行數,所以宣告時也可以直接去掉裡面的括號
```cpp
int score[2][6]={
82,65,99,88,84,76,
100,85,88,90,99,85
}
```
---
例題1
---
>[e973: 3. 滿意度調查 (Survey of Satisfaction)](https://zerojudge.tw/ShowProblem?problemid=e973 "點選看題目")
```cpp=
#include <iostream>
using namespace std;
main()
{
long long int n;
int i, j, x;
int a[10];
for(i=0 ; i<10 ; i++)
{
a[i] = 0;
}
cin>>n;
while(n>0)
{
x = n%10;
a[x] ++;
n/=10;
}
for(i=18 ; i>0 ; i--)
{
for(j=0 ; j < 10 ; j++)
{
if(a[j] == i) cout<<j<<" ";
}
}
}
```
>>
#### 程式的重點:
用``long long int``來宣告輸入的變數 N
在第 8 行使用 **for** 迴圈來初始化所有陣列的變數為 **0**
接下來的 **while** 迴圈把遇到的數字次數儲存起來
最後的 **for** 迴圈判斷各個數字出現的次數,因為題目規定的數字大小最多有 18 位數
2^63-1 的位數和 2^63 的位數一樣,因為個位數字是不為零的偶數
$$\begin{gather}
log(2^{63})=63log2 \\
\Rightarrow63log2\approx 18.9<19
\end{gather}$$
>
,所以就從 18 開始往下數,如果對應到的出現次數一樣,就印出``cout``,也要注意題目要求如果有數字出現次數一樣,數字較小的就輸出在前面,因此在第 21 行的迴圈裡``j``從 0 往上執行。