0

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]);
  }   
}
2
Contributors
3
Replies
18
Views
2 Years
Discussion Span
Last Post by Moschops
Featured 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. Read More

1

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.

Edited by Moschops

0

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]]++;
    }

Edited by Moschops

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.