# how to find the frequency of elements in an array

• 08-23-2012, 06:21 PM
heman
how to find the frequency of elements in an array
hiii,
I am very newbie to this world of java.
can some one please help with the code for "how to find the frequency of elements in an array".
The program should be as simple as possible as i am a newbie..

thanks.

the output should be like this:

input array: 1,2,3,4,2,3,4,5,8
digit frequency
1 1
2 2
3 2
4 2
5 1
8 1

Any kind of help is welcome.
• 08-23-2012, 06:27 PM
JosAH
Re: how to find the frequency of elements in an array
Have you had a look at a SortedMap<Integer, Integer>? It makes it all so much easier (arrays are so Fortranesque).

kind regards,

Jos
• 08-23-2012, 07:02 PM
heman
Re: how to find the frequency of elements in an array
Bro I wish to accomplish my task only by using loops and conditional statements.
• 08-23-2012, 09:03 PM
JosAH
Re: how to find the frequency of elements in an array
Quote:

Originally Posted by heman
Bro I wish to accomplish my task only by using loops and conditional statements.

Your solution wouldn't be 'as simple as possible' ...

kind regards,

Jos
• 08-24-2012, 05:42 AM
heman
Re: how to find the frequency of elements in an array
Quote:

Originally Posted by JosAH
Your solution wouldn't be 'as simple as possible' ...

kind regards,

Jos

if it is not as simple as possible then kindly provide me any solution with only loops and conditional statements.
thanks:(-:
• 08-24-2012, 08:59 AM
DarrylBurke
Re: how to find the frequency of elements in an array
Go through this tutorial: Control Flow Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)

Then post your best efforts and if you still have problems, ask a specific question.

We don't do your homework for you here, but we're more than willing to help you learn enough to do it yourself.

db
• 08-24-2012, 10:41 AM
heman
Re: how to find the frequency of elements in an array
here is my code:

class Fre
{
public static void main(String ar[])
{

frequencycount(new int[]{1,2,3,3,2,1,1,1,5,6,5,8,9,6});

}

static void frequencycount(int x[])
{
int i=0,j=0;

int fr[]=new int[x.length];

for(i=0;i<fr.length;i++)
{
fr[i]=0;
}

/////calculating frequency
for(i=0;i<x.length;i++)

{
for(j=0;j<x.length;j++)
{
if(x[i]==x[j])
{

fr[i]++;

}
}
}

for(i=0;i<fr.length;i++)
{

System.out.println(" "+fr[i]);
}
}

}//class

it finds frequency of each element but does not print in a specific pattern what i wanted as i posted in my first thread.

```class Fre { public static void main(String ar[]) { frequencycount(new int[]{1,2,3,3,2,1,1,1,5,6,5,8,9,6}); } static void frequencycount(int x[]) { int i=0,j=0; int fr[]=new int[x.length]; for(i=0;i<fr.length;i++) { fr[i]=0; } /////calculating frequency for(i=0;i<x.length;i++) { for(j=0;j<x.length;j++) { if(x[i]==x[j]) { fr[i]++; } } } for(i=0;i<fr.length;i++) { System.out.println(" "+fr[i]); } } }//class```