Digit frequency query | help (SOLVED)

Can someone help me with that ‘if’ block . how its storing frequency.
question link- https://www.hackerrank.com/challenges/frequency-of-digits-1/problem

int main() 
{
    char a[1000];
    int c,num[10] = {0};
    scanf("%s",a);
    for(int i = 0 ;i <= strlen(a);i++)
    {
        if(isdigit(a[i]) > 0)
        {
            c = (a[i]) - '0';
            num[c] += 1;
        }
    }
    for(int i = 0; i<10;i++)
    {
        printf("%d ",num[i]);
    }
    return 0;
}

INPUT-lw4n88j12n1
OUTPUT- 0 2 1 0 1 0 0 0 2 0

In if block isdigit is checking if it is a number or not. If it is a number then ASCII value of 0 is subtracted because it was actually a character. Now after subtraction, it gives index which needs to be updated. For example, for ‘0’ it is 48, for ‘1’ it is 49. If we subtract then it will give 1, which is the required index

1 Like

thank you i got it… thank you for your precise explanation :grinning:

You can read about isdigit() function here : https://www.geeksforgeeks.org/isalpha-isdigit-functions-c-example/ .
a[i] - ‘0’ returns the difference between ASCII value of a[i] (48 - 57) and ‘0’ (48).
Example : If a[i] = ‘7’, then c = a[i]-‘0’ = 55 - 48 = 7. Then increase the count of 7 in the frequency array.

1 Like

for updating the values dont we need to write arr[10]={0,1,2,3,4,5,6,7,8,9} ?? or arr[10] = {0}; is same
like arr[]=={‘zero’,one…}
for encountering 0 we zero++;

The first one is initializing arr with different values at different index while the second one is initializing arr with 0 for all indexes.

1 Like

look first of all we have to check weather a[i] is a digit or not (using isdigit() we are doing this) after that, …suppose a[i] found to be a digit let say 9 but remember 9 is currently a string ‘9’ which is actually 57 in ascii, so we know that ‘0’ is 48 when we do c= (a[i])-‘0’
that is actually c= 57-48 = 9 so we will increase value at the position 9 to have a record.

INPUT-lw4n88j12n1
OUTPUT- 0 2 1 0 1 0 0 0 2 0
in this we got 4 once so a[4] = 1 and 8 twice so a[8] = 2

hope it helped … whatsapp p mil :stuck_out_tongue:

1 Like

thank you Hardik … okay :rofl: :sweat_smile:

1 Like