c - How is this array recording occurrences of each digit of input? -
c - How is this array recording occurrences of each digit of input? -
i learning c using k&r book, , came across programme shows utilize of arrays. programme uses array record occurrences of each digit(number) entered, rather having individual numbers stored(or think). other this, programme counts whitespaces , other characters. here programme -
#include <stdio.h> int main(int argc, const char * argv[]) { // insert code here... // printf("hello, world!\n"); int c,i,nwhite,nother; int ndigit[10]; nwhite=nother=0; for(i=0;i<10;i++) ndigit[i]=0; while ((c=getchar())!=eof) if (c>='0' && c<='9') { ++ndigit[c-'0']; } else if(c==' '||c=='\n'||c=='\t') ++nwhite; else ++nother; printf("digits = "); (i=0; i<10; ++i) printf("%d", ndigit[i]); printf("\n white space= %d, other=%d\n", nwhite,nother); homecoming 0; }
and here sample output-
my birthday 08081980 hello digits = 3100000031 white space= 5, other=18
it took me while figure out ndigit
array records number of times each digit occurs. example- 0
occurs 3 times in input.
however, couldn't figure out how array set through loop. @ beginning,
for(i=0;i<10;i++) ndigit[i]=0;
this loop sets every element of ndigit
array zero. then, didn't understand happens in if statement-
if (c>='0' && c<='9') { ++ndigit[c-'0']; }
that maybe due fact haven't come across type of code before. ++ndigit[c-'0']
look trying do? assume every digit entered in form of character , converted internally int through ascii value? c -'0'
look doing here?
many help on this.
you need remember character constants considered values of type int
in c. in particular, integer values.
in case, guaranted standard typical characters, english language alphabetical letters, or digits, have positive integer values, in range of values of char
. moreover, encoding schema of characters, it guaranted (by standard c) digits '0' '9' have contiguous codes. example, in typical case of ascii, have:
'0' == 48 '1' == 49 ... '9' == 57
now, sentence if (c>='0' && c<='9')
"asking" if value of c
in range of digits. then, expressión c - '0'
gives integer value of digit, easy check. example, if c == '3'
, have '3' - '0' == 51 - 48 == 3.
this important, because index of array starts @ 0 and, in program, array ndigit
intended hold info of j-th digit in j-th position of array. so, expressión ndigit[ '3' - '0' ]
same ndigit[3]
.
finally, create "count", need increment in 1 value stored in ndigit[3]
, increment operation done, achieved through ++
operator.
c arrays ascii
Comments
Post a Comment