i have a confusion in the body part of while loop .... what does the body part mean??????Code:int c,a[10]; while((c=getchar()!=EOF) { if(c>='0' && c<='9') ++a[c-'0']; }
i have a confusion in the body part of while loop .... what does the body part mean??????Code:int c,a[10]; while((c=getchar()!=EOF) { if(c>='0' && c<='9') ++a[c-'0']; }
If c is a digit, increment the element of a corresponding to the digit (i.e., count the frequency of the digit). Incidentally, you probably should initialise a.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
that's fine ... i know for array we increment the index for getting the next value...
but over here,
[code]
if(c>='0' && c<='9')
++a[c-'0'];
[\code]
what are we doing over here???
basically as we are writing 0 as a character '0' thus as c is an integer, '0' will be converted into it's ascii value 48 and thus it will be checked in the if condition and similary for '9'.... now when we write ++a[c-'0']
it means a[c-'0']=a[c-'0'] + 1 which i am confused ???
if you could explain it more it would be clear to me....
You are correct that the entered value is in ASCII. That is, digits '0' to '9' are really integers 48 to 57.
The 'if' statement checks that the character is within that range. You could have done it this way as well: if (c >= 48 && c <=57) but using the quoted chars is easier to read.
The c-'0' calculation removes that offset. We know '0' is 48, or you could have written it as c-48. It ensures the index becomes 0 to 9.
Counting number frequency. If the character provided by getchar() is between 0 and 9, then the corresponding element of the array is increased by one. This might be clearer:
Since it does not matter whether it is a post or pre increment. As you say, the ASCII value of '0' is 48. So, eg, if c == '5' (ASCII 53), then element 53-48 = 5 will have one added to it.Code:a[c-'0']++;
Make sense?
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
thanks...
got it...