# Digit frequency query | help (SOLVED)

Can someone help me with that ‘if’ block . how its storing frequency.
question link- Digit Frequency | HackerRank

``````int main()
{
char a;
int c,num = {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 You can read about isdigit() function here : isalpha() and isdigit() functions in C with cstring examples. - GeeksforGeeks .
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={0,1,2,3,4,5,6,7,8,9} ?? or arr = {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 = 1 and 8 twice so a = 2

hope it helped … whatsapp p mil 1 Like

thank you Hardik … okay  1 Like