学习C第一章入门篇6: 数组
书中本章的例子的目的是来数每一个数(0-9),空格字符(空格,制表符,换行符) 以及 其它所有字符分别出现的次数。
例子程序代码如下:
#include <stdio.h>
/* count digits, white space, others */
main() {
int c, 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' && c<='9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i=0; i<10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
}
}
认真感受下应该就可以懂了。
书后练习题1-13:
Write a program to print a histogram of the lengths words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.
我写的版本:
/* Histogram to prints the lengths of the words --- Horizontal */
#include <stdio.h>
#define INSIDE 1 // Inside a word
#define OUTSIDE 0 // Outside a word
main() {
int c; // Variable that receives the value from getchar()
int length = 0; // Variable that counts the length of a word
int state = OUTSIDE; // Variable that helps us to know the status
while ((c = getchar()) != EOF) {
// Check, if we are in a word now or not.
if ((c==' ')||(c=='\n')||(c=='\t')) {
// We are not in a word anymore, we should print the information of the word to the console.
if (state == INSIDE) {
// Print Information
putchar('\t');
int i;
for (i=0; i<length; i++) {
putchar(219);
}
putchar('\n');
// Initialize the Variables
state = OUTSIDE;
length = 0;
}
} else {
// We are in a word.
if (state == OUTSIDE) state = INSIDE;
putchar(c);
length++;
}
}
}
上面这个是横向版的,纵向版的还得自己写个List,有点懒, 不写了 就这样。
书后练习题1-14:
Write a program to print a histogram of the frequencies of different characters in its input.
我写的版本:
/* Histogram that prints the frequencies of different characters in its input */
#include <stdio.h>
main() {
int c; // Variable that receives the return value of the function getchar()
int characters[128]; // An array that holds the numbers of occurrence of the characters.
// Initialize
int i;
for (i=0; i<128; i++) {
characters[i] = 0;
}
while ((c=getchar()) != EOF) {
if (c=='\n') {
characters['\n']++;
for (i=0; i<128; i++) {
printf("ASCII Dec Number: %d Frequencies: %d\n", i, characters[i]);
}
} else {
characters[c]++;
}
}
}
参考: 《The C Programming Language》- Chapter 1.6