简体   繁体   中英

C Program To Count Each Digit In A Number using 2 Arrays

I'll need to write a function called void digits (int arr [], int size, int statistics []) that receives an array of integers and its size, as well as another array, called statistics, in size 10. The function changes the array statistics so that it contains The number of impressions of each told in the numbers of the array array. That is, statistics [i] contains the quantity The appearances of the story i. The function does not change the " arr " array, and does not print anything. For example, if arr [] = {438,439,440,441,442,443,444} then at the end of the function run statistics [] = {1,1,1,3,13,0,0,0,1,1} . That is, the digit 0 appears once in the "arr" array, the digit 1 Appears once in the "arr" array, etc.

You should use mod and division to filter out the digits. then use the digit as an index in the statistics array and increment the relevant element.

Something like this:

void digits(int arr [], int size, int statistics []) {
  for(int i=0 ; i<10 ; i++) {  
    statistics[i] = 0
  }
  for (int i=0 ; i< size ; i++) {
     int remainder = arr[i];
     do{
        int digit = remainder % 10;
        remainder = remainder / 10;
        statistics[i]++;
     }while(remainder) ;
  }
}

It is a good habit of writing testcases for your code too, for a quick hack like this you don't need a fancy setup to run testcase. Just setup a few function calls from main() to you function and print the result in a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM