I was going through the book "The C Programming language" by Kernighan and Ritchie and I am stuck at a topic.
Topic number 1.6 talks about Arrays. In the book, they have included a program that counts the digits, white spaces and other characters. The program goes like 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, I don't understand the purpose of the first for loop that is :
for(i=0;i<10;++i)
ndigit[i]=0;
And secondly, I can't understand the logic behind this part of the while loop:
if (c>='0' && c<='9')
++ndigit[c-'0'];
I really need someone to explain me the logic behind the program so that I can move further with C programming.
Thanks for the help!
This loop
for(i=0;i<10;++i)
ndigit[i]=0;
is used to set all elements of array ndigit
to 0. The array will count numbers of eneterd digits.
Instead of this loop you could initially initialize all elements of the array to 0 when it was declared.
int ndigit[10] = { 0 };
As for this statement
if (c>='0' && c<='9')
++ndigit[c-'0'];
then if the entered char is a digit c>='0' && c<='9'
then expression c-'0'
gives you the integer value of the digit. Characters that correspond to character constant '0' - '9'
internally in the computer memory represented by their ASCII or some other coding scheme codes. For example cgaracter '0'
in ASCII has internal code 48
, character '1'
- 49
, character '2'
- 50
and so on. For example in EBCDIC cgaracter '0'
has another code 240
, character '1'
- 241
and so on.
The C Standard guarantees that all digits follow each other.
So if variable c
keeps some digit then expression c - '0'
gives number from 0 (if c keeps '0' ) to 9 (if c keeps character '9' ).
This value (from 0 to 9) is used as an index in array ndigit
.
For example let assume that c keeps character '6'
. Then c - '0'
will equal to integer number 6. So ndigit[6] is increased
++ndigit[c-'0']
This element of the array with index 6 counts how many times character '6' was entered.