# C語言 陣列求救!可以寫讓我參考的code嘛?順便加註解!我

Given N (N<=1000) space-separated single-digit numbers, write a program to draw the histogram graph according to the number of the occurrences of the digits 0~9.

Example 1

Input:

15 2 8 8 7 8 2 2 8 7 4 8 4 4 0 3

Output:

1:

5:

6:

9:

0:-

3:-

7:--

2:---

4:---

8:-----

The first number in the input is N which is followed by N single-digit numbers. As shown in above, the leftmost column from top to bottom in the histogram graph lists the digits 0~9 in the ascending order of their respective frequencies. For example, since both the digits 0 and 3 have 1 occurrence in the inputted numbers, their histograms are thus drawn with 1 dash and appear after the histograms of digits 1, 5, 6, and 9, all of which having 0 occurrence in the inputted numbers. In case multiple digits have the same number of occurrences, output them in ascending order. For the above example, the digits 1, 5, 6, and 9 have 0 occurrence, their histograms are drawn with no dash and outputted in the order of 1, 5, 6, and 9 (because 1<5<6<9).

Example 2

Input:

5 9 8 9 0 6 2 0 8 9 5 1 2 4 2 1 1 7 8 9 4 3 9 2 3

Output:

6:-

7:-

0:--

3:--

4:--

5:--

1:---

8:---

2:----

9:-----

我真的很想學好陣列,所以請各位教教我這題!

### 1 Answer

- prisoner26535Lv 78 years agoFavorite Answer
void

my_sort(

int *i,

int *o,

int n

){

int j, k, t;

for(j=0; j<n; ++j){

o[j] = j;

for(k=j; k > 0; --k)

if (i[o[k]] < i[o[k-1]])

t = o[k], o[k] = o[k-1], o[k-1] = t;

}

return;

} // end of my_sort()

int main(

int argc,

char *argv[]

){

int cnt[10] = {0}; // instance counts

int srt[10]; // sorted in ascending order

int N; // number of numbers

int i, j;

// read the inputs and range check

scanf("%d", &N);

// check input number

if (N < 0 || 1000 < N) return 1;

for(i = 0; i < N; ++i){

scanf(" %d", &j);

if (0 <= j && j < 10) ++cnt[j];

}

// sort the input []

my_sort(cnt, srt, (int)sizeof(cnt)/sizeof(cnt[0]));

// print out the graph

for(i=0; i < (int) (sizeof(cnt)/sizeof(cnt[0])); ++i){

printf("%d: ", srt[i]);

for(j = cnt[srt[i]]; j > 0; --j) printf("-");

printf("\n");

}

return 0;

}

- Login to reply the answers