Frequency Of Array Elements

Frequency Of Array Elements


Write a program to print the frequency of each element in an array.

   import java.io.*;

    class Array_Frequency
    {
    public static void main ( String agrs[])throws IOException
    {
        BufferedReader obj= new BufferedReader(
            new InputStreamReader(System.in));
    int i,j,m,f;
    boolean flag = false;

    System.out.println("Enter the length of the array : ");
     m = Integer.parseInt(obj.readLine());
     int a[] = new int[m];

    System.out.println("Enter "+m+" elements for the Ist array");

    for(i = 0; i < m; i++)
    {
        a[i] = Integer.parseInt(obj.readLine());
    }

    for(i = 0; i < m; i++)
    {
        f = 1;  //Frequency will be atleast 1

        for(j = i + 1; j < m; j++)
        {
            //find the frequency by comparing
            if(a[i] == a[j] && a[j]!=0){

                //set a[j] to 0 so that frequency is not duplicated
                //for a particular element
                a[j] = 0;
                 f++;
            }
        }
    if(a[i] != 0)
    System.out.println("Frequency of " + a[i] + " : " + f);
    }

  }
}

Have something to say? Log in to comment on this post.

0 comments