Count number of occurrences of a digit within a string

后端 未结 2 1685
遥遥无期
遥遥无期 2021-01-24 04:23

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 

        
2条回答
  •  离开以前
    2021-01-24 04:55

    Consider this modified code:

    #include 
    #include 
    
    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++) { //i = current digit
        for (int j = 0; j < 10; j++) { //j = index in array
          if (i == numbers[j]) {
            count++;
          }
        }
        printf("Number %d has occured %d times \n", i, count);
        count = 0;
      }
    }
    

    Output:

    Number 0 has occured 0 times 
    Number 1 has occured 2 times 
    Number 2 has occured 1 times 
    Number 3 has occured 1 times 
    Number 4 has occured 1 times 
    Number 5 has occured 3 times 
    Number 6 has occured 2 times 
    Number 7 has occured 0 times 
    Number 8 has occured 0 times 
    Number 9 has occured 0 times 
    

    You were counting how often each digit occuring in the array (including duplicate digits in the array) occured.

提交回复
热议问题