ch3-count (Digits, whitespace, other characters)

Chapter_3     Exercise_3-1 Exercise_3-2







count.c     K&R, p. 59         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

// count types of characters: digits, whitespace, other
int main()
{
int c, i, nwhite, nother, ndigit[10];

nwhite = nother = 0; // initialize
for (i = 0; i < 10; i++)
{ndigit[i] = 0;} // initialize

while ((c = getchar()) != EOF)
{
switch(c)
{
case '0' : case '1': case '2' : case '3' : case '4' :
case '5' : case '6': case '7' : case '8' : case '9' :
ndigit[c-'0']++;
break; // without break, execution continues to the remaining cases
case ' ' : case '\t' : case '\n' :
nwhite++;
break;
default: // for all the other characters (possible cases)
nother++;
break; // optional break of the end
}
}

printf("digits:\t\t");
for (i = 0; i < 10; i++)
{printf("%d\t", i);}
putchar('\n');
printf("occurrences:\t");
for (i = 0; i < 10; i++)
{printf("%d\t", ndigit[i]);}
putchar('\n');

printf("whitespaces:\t%d\n", nwhite);
printf("others:\t\t%d\n", nother);

return 0;
}
/*
gcc count.c -o count
./count // input from keyboard
// type the input, then press CTRL+D in Linux, CTRL+Z, then Enter in Windows (EOF)

./count < count.c // input from source file
digits: 0 1 2 3 4 5 6 7 8 9
occurrences: 17 22 4 6 3 5 7 6 8 4
whitespaces: 645
others: 966

./count < count // input from binary file
digits: 0 1 2 3 4 5 6 7 8 9
occurrences: 18 7 16 3 8 8 7 1 16 5
whitespaces: 70
others: 16681
*/





Note:  See also countc from Chapter_1, Sec. 1.6.









Chapter_3     Exercise_3-1 BACK_TO_TOP Exercise_3-2



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo