Find Frequency C++

the negative value not count properly. pls help.
Thank you.

#include <iostream>

using namespace std;

void main()
{
int a[10] = {1,2,2,2,3,3,-3,-2};
int f[10] = {0};
int i;
for (int i = 0; i<10 ; i++){
f[a[i]]++;
}
for (i = -2; i<10; i++){
cout << i <<" appears "<<f[i]<<" times."<<endl;
}


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
// using namespace std; // *** avoid

/*void*/ int main() // *** main must return int
{
    const int a[] = { 1, 2, 2, -2, 2, -2, 3, -2, 3, -3, -2 };
    const int N = sizeof(a) / sizeof( a[0] ) ;

    // find the smallest and biggest elements
    int smallest = a[0] ;
    int biggest = a[0] ;
    for( int i = 1 ; i < N ; ++i )
    {
        if( a[i] < smallest ) smallest = a[i] ;
        if( a[i] > biggest ) biggest = a[i] ;
    }

    // we can't use a c-style array for f; size is not known at compile time
    // http://www.mochima.com/tutorials/vectors.html
    std::vector<int> f( (biggest-smallest) + 1 ) ;
    for( int i = 0 ; i < N ; ++i ) ++f[ a[i] - smallest ] ;

    for( std::size_t i = 0 ; i < f.size() ; ++i )
    {
        const int count = f[i] ;
        if( count > 0 )
        {
            const int n = i + smallest ;
            std::cout << n << " appears " << count << " time" ;
            if( count > 1 ) std::cout << 's' ;
            std::cout << ".\n" ;
        }
    }
}

http://ideone.com/WUHgVi
Thank you very much.
Topic archived. No new replies allowed.