arrays - Check whether the input is digit or not in C programming -
i reading book: the c programming language - kernighan , ritchie (second edition) , 1 of examples having trouble understanding how check whether input digit or not. example on page 22, explaining under array chapter.
below example.
#include <stdio.h> /* count digits, white space, others */ main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; (i = 0; < 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; < 10; ++i) { printf(" %d", ndigit[i]); } printf(", white space = %d, other = %d\n",nwhite, nother); } for example, confused me author mentioned line ++ndigit[c-'0'] checks whether input character in c digit or not. however, believe if statement ( if (c>= '0' && c<= '9') ) necessary, , check if c digit or not. plus, not understand why [c-'0'] check input(c) digit or not while input variable (c) subtracted string-casting ('0').
any suggestions/explanations appreciated.
thanks in advance :)
the if statement checks whether character digit, , ++ndigit[c-'0'] statement updates count digit. when c character between '0' , '9', c-'0' number between 0 , 9. put way, ascii value '0' 48 decimal, '1' 49, '2' 50, etc. c-'0' same c-48, , converts 48,49,50,... 0,1,2...
one way improve understanding add printf code, e.g. replace
if (c >= '0' && c <= '9') ++ndigit[c-'0']; with
if (c >= '0' && c <= '9') { ++ndigit[c-'0']; printf( "is digit '%c' ascii=%d array_index=%d\n", c, c, c-'0' ); }
Comments
Post a Comment