Archived

This topic is now archived and is closed to further replies.

White Crow

Array subscription problem

Recommended Posts

Hi I have been reading a book for a couple of days now and there is a source code example which I don''t fully understand: void main(void) { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother =0; for(i = 0; i<10;++i) ndigit = 0; while ((c = getchar()) !=''q'') if ( c >=''0'' && c<=''9'') ++ndigit[c-''0'']; //this is my problem else if (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); } the problem is that why should I write ++ndigit[c-''0''] instead of ++ndigit[c]? In my eyes it is the same but in the eyes ow the author (and my compiler) it is not. Who can help me?

Share this post


Link to post
Share on other sites
quote:
the problem is that why should I write ++ndigit[c-''0''] instead of ++ndigit[c]?


0 is a number,
''0'' is a character,
a character is stocked as a 8 bits number, I think the ASCII-code of ''0'' is 48, so ''1''->49, ''2''-> 50...

also,
''0''-''0'' = 48 - 48 = 0,
''1''-''0'' = 49 - 48 = 1,
...

and you can find the number you want.

------------------------
- Seby -
www.dfhi-bomber.fr.st

Share this post


Link to post
Share on other sites
quote:
Original post by White Crow
Hi

I have been reading a book for a couple of days now and there is a source code example which I don''t fully understand:

void main(void)
{
int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother =0;

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

while ((c = getchar()) !=''q'')
if ( c >=''0'' && c<=''9'')
++ndigit[c-''0'']; //this is my problem
else if (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);
}


the problem is that why should I write ++ndigit[c-''0''] instead of ++ndigit[c]? In my eyes it is the same but in the eyes ow the author (and my compiler) it is not. Who can help me?




1) You use getchar
==>You read a character
==>The character is one that has ASCII code, its NOT a number(digit), its an ASCII code

2) You are using the same array namely ndigit to store EITHER white space OR tab OR newlines OR digits OR others.Right? Are LL these numbers?So that''s a hint that you are NOT.

3)If you write ndigit[c], you would be storing the number of storing the *number of times you found a digit* at the location ndigit[ascii code of that digit] which is NOT the same as
ndigit[c-''0''].
For example to store the number of times you found 1, you want to store it at ndigits[1], right?But if you use ndigits[c], then, yuo end up storing the value at
ndigit[ascii code of 1]
==>ndigit[49] and this is NOT the same as ndigits[1]
This is NOT what you wanted, is it?

Share this post


Link to post
Share on other sites