So I'm trying to count the number of occurrences of each digit within an array.

My code I've got so far looks like the following:

#include <stdio.h>
#include <string.h>

int main()
{
  int numbers [10]= {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
  int count = 0;

  for(int i = 0; i < 10; i++)
  {
    for (int j = 0; j < 10; j++)
    {
      if (numbers[i] == numbers[j])
      {
        count++;
      }
    }
    printf("Number %d has occured %d many times \n", numbers[i], count);
    count = 0;

  }
} 

Only the output I get is the following:

Number: 1       Occurence: 2
Number: 4       Occurence: 1
Number: 5       Occurence: 3
Number: 5       Occurence: 3
Number: 5       Occurence: 3
Number: 6       Occurence: 2
Number: 6       Occurence: 2
Number: 3       Occurence: 1
Number: 2       Occurence: 1
Number: 1       Occurence: 2 

I only want to count the occurrence of EACH digit, it seems to be counting duplicates.

How can I correct this code? Can someone point me in the right direction.

Many thanks

Alonso

I would have to say that you need a flagging system which marks a integer element when its been counted.

Are you sure this is C?

for(int i = 0; i < 10; i++)
{
...
}

Yes, this is C. Changing the outer for loop to be < 10 counts each integer element. Thanks very much.

Keep a frequency table:

int numbers[] = {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
int freq[10] = {0};

for (int i = 0; i < sizeof numbers / sizeof *numbers; i++) {
    if (numbers[i] >= 0 && numbers[i] < 10) {
        ++freq[numbers[i]];
    }
    else {
        printf("Invalid digit: %d\n", numbers[i]);
    }
}

for (int i = 0; i < 10; i++) {
    printf("%d has occured %d time(s)\n", i, freq[i]);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.