Answer the question
In order to leave comments, you need to log in
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.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question