Why do we write ++ndigit in the counting program for numbers, symbols, white space and other characters?

Why do it at all ++ ?

 #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); } 
  • @Ivan Bratchikov, To format the code, select it with the mouse and click on the {} button of the editor. - etki

2 answers 2

Everything is very simple. ndigit is an array that stores the number of digits. If the current character is a digit (in the previous line condition), then you need to take it into account. Parse the string

 ++ndigit[c - '0' ]; 

In pieces.

The variable c stores the current figure (this is guaranteed so because of the condition). In si (and in other languages) all characters have their code ( aski code ). And the most interesting - they are all ordered. At zero, the code is 48, at the unit - 49, and at the nine - 57. Code c - '0' is a very famous trick that converts the code to a number. That is, the symbol '7' will correspond to the number 7.

Two plus points are the increment operation.

Therefore, the code ++ndigit[c - '0' ]; can be written так ndigit[текущая_цифра] = ndigit[текущая_цифра]+1 .

After the passage of the entire line in the ndigit array, the number of digits is broken down by each digit.

  • why ndigit [current_number] +1, why add +1? - Ivan Bratchikov
  • Uh ... Well, the increase in nwhite by 1 when meeting the whitespace character is not surprising? Here is the same thing. ndigits[0] contains the number of characters '0' (initially - none), we meet zero - we increase the counter by 1. In ndigits[1] the number of characters '1' is stored, we act in the same way, etc. - user6550
  • Thank! One more thing . And how to determine what should be the number in the curly brackets of the array (ndigit [10])? How generally to define when what character to put in these curly brackets? - Ivan Bratchikov

Postincrement would look more logical, of course:

 ndigit[c-'0']++; 

why do this ++

By condition, it is not obvious that you need to count the number of different digits. To calculate the digits of all it would be enough one variable. But the code counts how many different digits, for which the ndigit array is ndigit (in the first element the number of zeros accumulates, in the second - the number of ones, etc.).