-1

I'm trying to find the number of occurrence of digit in input (typed number). I'm confused with subscript expression of array in the expression ++ndigit[ c - '0'].

Here the code

#include <stdio.h>
/* count digits, white space, others*/ 

main() { 

       int c, i, nwhite, nother;
 
       int ndigit[10];
 
       nwhite = nother = 0; 
 
       for(i = 0; i < 10; ++i)

          {ndigit[i] = 0;}


       while  ((c = getchar()) I= EOF) 

        {if (C >= '0' && C <= '9') 

           {++ndigit[c-'0'];}
       /*here i stucked explain me how 
            subscript 
          expression going too work*/

       elseif (c ==' '; c == '\n'; c =='\t'){     
           ++nwhite; }
       else {
       ++nother; }
        }

         printf("digits ="); 


      for (i = 0; i < 10; ++i){

          printf(" %d", ndigit[i]);
      }
      printf(" , white space = %d, other = %d\n", nwhite, nother);
    }
Dada
  • 6,313
  • 7
  • 24
  • 43
Nil
  • 1
  • 1

1 Answers1

0

char is just a 7-bit number. The computer encodes those numbers to a character using whatever character encoding your computer uses (mostly ASCII).

In ASCII, 0 has a value of 48, 1 has a value of 49, ... , 9 has a value of 57

So:

If c is 48 (or '0'), c - '0' = 48 - 48 = 0, ndigit[c - '0'] = ndigit[0]
If c is 49 (or '1'), c - '0' = 49 - 48 = 1, ndigit[c - '0'] = ndigit[1]

...
If c is 58 (or '9'), c - '0' = 57 - 48 = 9, ndigit[c - '0'] = ndigit[9]

So this is a way to map the ASCII number value to number value. And ++ is simply increment. So: if ndigit[0] = 0; ++ndigit[0] then ndigit[0] = 1

  • `char` is at least eight bits, C implementations commonly support more than just the seven-bit ASCII codes, and there is no need to mention ASCII in this answer, because `ndigit[c - '0']` works based solely on the specifications in the C standard; it does not need ASCII. – Eric Postpischil Nov 16 '21 at 12:03