Frequency of Array Elements

• 12-21-2011
Zaheer Attar
Frequency of Array Elements
hi eveyone,

i want calculate the frequency of array element. so please i want small program of it & want easy to explain hope you all friand help me in making best program.i also write some steps of it but still some problems. so i want your program & compare with my program....so please replay fast:)
• 12-21-2011
laserlight
What have you tried?
• 12-21-2011
alegro
• 12-21-2011
Zaheer Attar
Code:

```#include<stdio.h> #include<conio.h> void main() { int a[5],freq=1,i,j,k,n=5; clrscr(); printf("Enter Elements=\n"); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) { for(j=0;j<5;j++) if(a[i]==a[j]) { freq++; } printf("Elements\tFrequency\n"); . . .```
No idea guys
• 12-21-2011
Amberlampz
This is wrong:

Code:

```for(i=0;i<5;i++) { for(j=0;j<5;j++) if(a[i]==a[j]) { freq++; }```
For every element in the array, you're cycling through the whole array again. Think about what freq would be if your array contained '11234' and why it's not giving you the correct answer.
• 12-21-2011
Imagine if you were doing this by hand. You might have a tally column like this:

Number Number of Times in the Array
==========================
0 3
1 5
2 4
3 1
4 3

etc.

When you were done tallying up the totals, you could just refer to that list you made above ^^^^.

Now, image that instead of a tally list, you used an int array, and used array[0] to tally up all the zero's, and
array[1] to tally up all the one's, and
array[2] to tally up all the two's,

etc.

I call that a "distribution array", but "frequency" or tally is also good. Note how easily it works in a loop, where:
Code:

```for(i = 0; i < SIZE; i++) {   array[yourArray[i]]++;```
Now that's pretty slick! Remember how that was done - this is a nice tool to keep in your programming toolbox.
• 12-23-2011
Zaheer Attar
Thanks Guys But I Write New Program with new logic....
Code:

```#include<stdio.h> #include<conio.h> void main() { int a[20],fr=0,n clrscr(); printf("How Many Elements..\n"); scanf("%d",&n); printf("Enter Elements..\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("Which Elements Frequency do you want..?\n"); scanf("%d",&op); for(i=0;i<n;i++) { if(a[i]==op) { fr++; } } printf("%d's Frequency is %d",op,fr); getch(); }```