O
O
Oleg Filimonenko2018-02-17 23:18:00
C++ / C#
Oleg Filimonenko, 2018-02-17 23:18:00

Explain how the cycle works from Kernighan's textbook?

Hello! I ask for help from those who, by virtue of their knowledge, will be able to explain to me, a hellowalder, the essence of the following cycle construction. Here is an excerpt from the textbook:

Now let's write a program that counts separately each digit, separator characters
(spaces, tabs and newlines) and all other characters. This is a somewhat artificial program, but it
will allow us to demonstrate a few more features of the C language in one example. There are
twelve categories of input characters. It is convenient to store all ten digit counters in an array, and not as
ten separate variables. Here is one version of this program:
#include <stdio.h>
/* подсчет цифр, символов-разделителей и прочих символов */
main()
{
int с, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i]= 0;
while ((c = getchar()) != EOF)
if (c >= '0' && с <= '9' )
++ndigit[c - '0' ];
else if (c == ' ' || с == '\n' || с == '\t')
++nwhite;
else
++nother;
printf ("цифры =");
for (i=0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf (", символы-разделители = %d, прочие = %d\n", nwhite, nother);
}

............
The above program relies on certain properties of digit encoding. For example, the test
if (c >= '0' && c <= '9' ) ...determines if the character in c is a digit. If so, then
c - '0'
is the numeric value of the digit. The above is true only if for the series of values ​​'0' ,
'1',...,'9' each next value is 1 greater than the previous one. Fortunately, this rule is respected in
all character sets.

Actually, the question is: what exactly does this operand do: ++ndigit[c - '0' ]; ? What does this, at first glance, absolutely incomprehensible operation have to do with encoding? "Readable character minus zero"? I would appreciate any answer.
Thanks to everyone who will respond.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2018-02-17
@Redproxima

The c language does not distinguish between an unsigned 8-bit integer and the ASCII character it encodes,

'0' == 48;
'1' == 49;
  и т.д.

So the `digit symbol` is '0' == the number written by that digit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question