c - Topic 1.6 by Kernighan and Ritchie -


i going through book "the c programming language" kernighan , ritchie , stuck @ topic.

topic number 1.6 talks arrays. in book, have included program counts digits, white spaces , other characters. program goes this:

#include <stdio.h>   main(){        int c,i,nother,nwhite;         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=='\t'||c=='\n')                 ++nwhite;             else                 ++nother;               printf("digits:");             for(i=0; i<10;++i)                 printf(" %d",ndigit[i]);              printf(", white space = %d, other = %d\n",  nwhite, nother);   } 

first, don't understand purpose of first loop :

 for(i=0;i<10;++i)              ndigit[i]=0; 

and secondly, can't understand logic behind part of while loop:

if (c>='0' && c<='9')                 ++ndigit[c-'0']; 

i need explain me logic behind program can move further c programming.

thanks help!

this loop

for(i=0;i<10;++i)              ndigit[i]=0; 

is used set elements of array ndigit 0. array count numbers of eneterd digits.

instead of loop initialize elements of array 0 when declared.

int ndigit[10] = { 0 }; 

as statement

if (c>='0' && c<='9')                 ++ndigit[c-'0']; 

then if entered char digit c>='0' && c<='9' expression c-'0' gives integer value of digit. characters correspond character constant '0' - '9' internally in computer memory represented ascii or other coding scheme codes. example cgaracter '0' in ascii has internal code 48, character '1' - 49, character '2' - 50 , on. example in ebcdic cgaracter '0' has code 240, character '1' - 241 , on.

the c standard guarantees digits follow each other.

so if variable c keeps digit expression c - '0' gives number 0 (if c keeps '0' ) 9 (if c keeps character '9' ).

this value (from 0 9) used index in array ndigit.

for example let assume c keeps character '6' . c - '0' equal integer number 6. ndigit[6] increased

++ndigit[c-'0'] 

this element of array index 6 counts how many times character '6' entered.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -