Hey guys, seems like im doing something wrong here 2 occurs 4198861 times* in an array of size 100, i need another set of eyes if anyone can point me in the right direction

#include <stdio.h>

//proto
void printOccurrence(int countArray[], int countSize);


//main
int main(void) 
{
    //variables
    int arraySize = 99;
    int countSize = 9;
    int i = 0;
    int j = 0;
    int number = 0;
    int array[arraySize];
    int countArray[countSize];

    //initialize arrays to 0
    for(i=0;i<=arraySize;i++)
    {
        array[i] == 0;
    }
    for(j=0;j<=countSize;j++)
    {
        countArray[j] == 0;
    }

    //random number setup
    srand(time(NULL));//tell rand to look at the clock


    //fill array with random numbers
    for(i=0;i<=arraySize;i++)
    {
        number = rand()%10;/* generate a number from 0 - 9 */
        array[i] = number;
    }


    //get the number of times 0-9 occurs in the array
    for(i=0;i<=countSize;i++)
    {
        for(j=0;j<=arraySize;j++)
        {
            if(array[j] == i){
                countArray[i] += 1;
            }
        }
    }

    //print
    printOccurrence(countArray,countSize);


    return (0);
}
void printOccurrence(int countArray[], int countSize)
{
  int i;
  for(i=0;i<=countSize;i++)
  {
      printf("%d occurred %d times\n",i,countArray[i]);
  }   
}

Recommended Answers

Line 26 is testing for zero. I suspect you meant = rather than ==

You could have found this by printing out the values of the array after you zeroed it, to check it was being set correctly at the start.

Jump to Post

All 3 Replies

Line 26 is testing for zero. I suspect you meant = rather than ==

You could have found this by printing out the values of the array after you zeroed it, to check it was being set correctly at the start.

Thanks alot i missed that, line 26 and line 22 change == to =

While I'm here, your algorithm for counting seems a bit excessive. You traverse the array of random numbers ten times. You could just do it once. Something like:

    //go through array
    for(i=0;i<=arraySize;i++)
    {
      // increment the right element in countarray
      countarray[array[i]]++;
    }
Be a part of the DaniWeb community

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