ch1-countc (Count digits, whitespace, other characters)

Chapter_1     Exercise_1-12 Exercise_1-13-1







countc.c     K&R, p. 22         download


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

// counts digits, whitespaces, other characters

int main()
{
int c, i;
int nwhite = 0, nother = 0;
int ndigit[10];

for (i = 0; i < 10; i++)
{ndigit[i] = 0;}

while ((c = getchar()) != EOF)
{
if (c >= '0' && c <= '9')
{++ndigit[c-'0'];}
else if (c == ' ' || c == '\t' || c == '\n')
{++nwhite;}
else {++nother;}
}

printf("digits = \t");
for (i = 0; i < 10; i++)
{printf("%3d", i);}
putchar('\n');
putchar('\t');putchar('\t');
for (i = 0; i < 10; i++)
{printf("---");}
putchar('\n');
printf("occurrences = \t");
for (i = 0; i < 10; i++)
{printf("%3d", ndigit[i]);}
putchar('\n');
printf("whitespaces = \t%d\n", nwhite);
printf("others = \t%d\n", nother);
}
/*
gcc countc.c -o countc
./countc // input from keyboard
Hello!
0 1 2 3 4 5 6 7 8 9
digits = 0 1 2 3 4 5 6 7 8 9
------------------------------
occurrences = 1 1 1 1 1 1 1 1 1 1
whitespaces = 11 // 9 blanks, 2 newlines
others = 6
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)

./countc < countc.c // input from source file
digits = 0 1 2 3 4 5 6 7 8 9
------------------------------
occurrences = 18 31 5 8 7 6 13 11 8 9
whitespaces = 514
others = 964

./countc < countc // input from binary file
digits = 0 1 2 3 4 5 6 7 8 9
------------------------------
occurrences = 16 7 16 5 8 8 7 1 17 6
whitespaces = 81
others = 16668
*/









Chapter_1     Exercise_1-12 BACK_TO_TOP Exercise_1-13-1



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo