Home > Mobile >  Digit Frequency calculating code in C not working
Digit Frequency calculating code in C not working

Time:09-23

So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    // takes string input
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s)   1);
    //turns the string to int
    int x = atoi(s);
    int temp = x, len = 0;
    //calculates string length
    while (x != 0) {
        x = x / 10;
        len  ;
    }
    x = temp;
    //parses through the string and matches digits with each number
    for (int j = 0; j < 10; j  ){
        int count = 0;
        for(int i = 0; i < len; i  ){
            if(x % 10 == j){
                count  ;
            }
            x = x / 10;
        }
        x = temp;
        printf("%d ", count);
    }
    return 0;
}

CodePudding user response:

To write a correct and reasonable digit-counting program:

  • Do not allocate any buffer for this.
  • Create an array to count the number of times each digit occurs. The array should have ten elements, one for each digit.
  • Initialize the array to zero in each element.
  • In a loop, read one character at a time.
  • Leave the loop when the read routine (such as getchar) indicates end-of-file or a problem, or, if desired, returns a new-line or other character you wish to use as an end-of-input indication.
  • Inside the loop, check whether the character read is a digit. If the character read is a digit, increment the corresponding element of the array.
  • After the loop, execute a new loop to iterate through the digits.
  • Inside that loop, for each digit, print the count from the array element for that digit.

CodePudding user response:

Your approach is way to complicated for a very easy task. This will do:

void numberOfDigits(const char *s, int hist[10]) {
    while(*s) {
        if(isdigit(*s)) 
            hist[*s - '0']  ;
        s  ;
    }
}

It can be used like this:

int main(void) {
    char buf[1024];
    int hist[10];

    fgets(buf, sizeof buf, stdin);

    numberOfDigits(s, hist);

    for(int i=0; i<10; i  ) 
        printf("Digit %d occurs %d times\n", i, hist[i]);
}

This can also be quite easily achieved without a buffer if desired:

int ch;
int hist[10];

while((ch = getchar()) != EOF) {
    if(isdigit(ch)) 
        hist[ch - '0']  ;
}
  • Related