user6005857 - 1 year ago 154
C Question

# Find frequency of digits in an int array in C

I am trying to write a function that takes the size of an array and an int array made up of digits as input and prints the frequency of each digit.

Sample input and output:

``````Input: [1,2,2,3,3,3]

Output:
1 occurs 1 times.
2 occurs 2 times
3 occurs 3 times.
``````

Here is my attempt (not the most elegant):

``````void freq(int size, int numArray[]) {
int one=0, two=0, thr=0, fou=0, fiv=0, six=0, sev=0, eit=0, nin=0;
int i, j;

for (i = 0; i < size; i++) {
for (j = 1; j < size; j++) {
if (numArray[i] == numArray[j] && numArray[i] == 1) {
one+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 2) {
two+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 3) {
thr+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 4) {
fou+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 5) {
fiv+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 6) {
six+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 7) {
sev+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 8) {
eit+=1;
}
else if (numArray[i] == numArray[j] && numArray[i] == 9) {
nin+=1;
}
}
}
printf("1 occurs %d times.\n", one);
printf("2 occurs %d times.\n", two);
printf("3 occurs %d times.\n", thr);
printf("4 occurs %d times.\n", fou);
printf("5 occurs %d times.\n", fiv);
printf("6 occurs %d times.\n", six);
printf("7 occurs %d times.\n", sev);
printf("8 occurs %d times.\n", eit);
printf("9 occurs %d times.\n", nin);
}
``````

This has problems. If I use the same example as above, this is what I get:

``````Input: [1,2,2,3,3,3]

Output:
1 occurs 0 times.
2 occurs 4 times.
3 occurs 9 times.
``````

The nested loop approach makes no sense, you only need to look at each digit once to count it. And of course an array makes more sense to keep the counters:

``````void freq(int size, const int *numbers)
{
unsigned int counts[10] = { 0 };
for(int i = 0; i < size; ++i)
{
const int here = numbers[i];
if(here >= 1 && here <= 9)
counts[here]++;
}
for(int i = 1; i < 10; ++i)
printf("%d occurs %u times\n", i, counts[i]);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download