|
|
|
#include <stdio.h>
/*
* Program to count the number of occurences of each digit, white space, and
* all other characters that the user types in
*/
int main ( void ) {
int ch, i, n_white, n_other, n_digit [10];
/* initialize all values to zero */
n_white = n_other = 0;
for ( i = 0; i < 10; i++ )
n_digit [i] = 0;
/*
* continue to read and process characters
*
* Note: the expression in the if statement must evaluate to zero or not-
* zero but it is also possible to do addition things in there
*
* ( ch = getchar () ) != EOF
*
* Gets a character from getchar(), assigns it to ch, and checks
* to see if it is equal to EOF. This is the easiest way to both
* get a copy of the character and test it
*/
while ( ( ch = getchar () ) != EOF ) {
switch ( ch ) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
/*
* this statment does many things. it is equivalent to something like
* int index = ch - '0'; find the digit
* int num = n_digit [index]; get the current number of that digit
* num++; increment it by one
* n_digit [index] = num; assign that value back to n_digit
*/
n_digit [ ch - '0' ]++;
break;
case ' ':
case '\n':
case '\t':
n_white++;
break;
default:
n_other++;
break;
}
}
/* print out the results */
printf ( "Digits =" );
for ( i = 0; i < 10; i++ )
printf ( " %d", n_digit[i] );
printf ( ", white space = %d, other = %d\n", n_white, n_other );
return ( 0 );
}