Thursday, May 1, 2014

Frequency of number in an array

Program to find number of times a given integer value has occurred in an array of integers.

let array a[]= {6,1,6,3,5,6,2,2,1,3,6,2}
output:
1 -- 2
2 -- 3
3 -- 2
5 -- 1
6 -- 4

The simple solution to the problem is to increment array value at a particular index where index value is equal to the number.

Program

#include<stdio.h>
int main()
{
       int a[]={6,1,2,5,6,3,2,2,2,1,4,2,8,4,3}; // size of a =15
       int b[10]; // size 10 is sufficient because maximum number in above array is 9
       int i;

       //assigning all elements of array b to 0    
       for(i=0;i<10;i++)
            b[i]=0;

       for(i=0;i<15;i++)
            b[a[i]]++;

       for(i=0;i<10;i++)
       {
           if(b[i]!=0)
              printf("%d -- %d\n",i,b[i]);
        }
       return 0;
}