Count number of occurrences of a digit within a string

后端 未结 2 1773
遥遥无期
遥遥无期 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 05:06

    You are going to need to arrays - one for the count (result) and one for the input. You should increment the index in the count array as you loop over the input numbers. I couldn't resist actually writing the code so, here you go, the following should work IN C++

    #include 
    #include 
    
    int main()
    {
      int inputNumbers [] = {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
      int resultCount [] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
      int countNumbers = sizeof(inputNumbers) / sizeof(inputNumbers[0]);
    
      for(int i = 0; i < countNumbers; i++)
      {
         resultCount[inputNumbers[i]]++;
      }
    
      for(int i = 0; i < countNumbers; i++)
      {
        printf("Number %d has occured %d times \n", i, resultCount[i]);
      }
    }
    

    Hope that helps.

提交回复
热议问题