A
arnuld
it works fine, any advice for improvement:
--------- PROGRAMME -------------
/* K&R2: 1.6 Arrays, exercise 1-13
STATEMENT:
write a programme to print a histogram of the lengths of words
in input. it is easy to draw the histogram with bars horizontal;
a vertical orientation i smore challenging.
NOTE: this code uses HORIZONTAL bars.
METHOD:
1.) we will count the length of each word by counting the
characters it has.
2.) we use an array where we will keep track of how many words
of a specific length we have encountered.
3.) for simplicity, we will not take into account any words
having more than 10 characters in it. extra characters will
simply be discarded.
*/
#include<stdio.h>
#define IN 1
#define OUT 0
#define MAXLENGTH 11
int main()
{
int i = 0;
int c = 0;
int nchar = 0;
int inspace = IN;
int wordlen[MAXLENGTH];
for(i = 0; i < MAXLENGTH; ++i)
wordlen = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '\t' || c == '\n')
{
if (inspace == OUT)
{
if(nchar > MAXLENGTH)
{
nchar = 0;
++wordlen[nchar];
}
else
++wordlen[nchar];
}
inspace = IN;
nchar = 0;
}
else
{
++nchar;
inspace = OUT;
}
}
for(i = 1; i < MAXLENGTH; ++i)
printf("%2d|: %d\n", i, wordlen);
return 0;
}
--------------- OUTPUT --------------
[arch@voodo kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-13.c
[arch@voodo kr2]$ ./a.out
like this
and
......................... about
1|: 0
2|: 0
3|: 1
4|: 2
5|: 1
6|: 0
7|: 0
8|: 0
9|: 0
10|: 0
[arch@voodo kr2]$
--------- PROGRAMME -------------
/* K&R2: 1.6 Arrays, exercise 1-13
STATEMENT:
write a programme to print a histogram of the lengths of words
in input. it is easy to draw the histogram with bars horizontal;
a vertical orientation i smore challenging.
NOTE: this code uses HORIZONTAL bars.
METHOD:
1.) we will count the length of each word by counting the
characters it has.
2.) we use an array where we will keep track of how many words
of a specific length we have encountered.
3.) for simplicity, we will not take into account any words
having more than 10 characters in it. extra characters will
simply be discarded.
*/
#include<stdio.h>
#define IN 1
#define OUT 0
#define MAXLENGTH 11
int main()
{
int i = 0;
int c = 0;
int nchar = 0;
int inspace = IN;
int wordlen[MAXLENGTH];
for(i = 0; i < MAXLENGTH; ++i)
wordlen = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '\t' || c == '\n')
{
if (inspace == OUT)
{
if(nchar > MAXLENGTH)
{
nchar = 0;
++wordlen[nchar];
}
else
++wordlen[nchar];
}
inspace = IN;
nchar = 0;
}
else
{
++nchar;
inspace = OUT;
}
}
for(i = 1; i < MAXLENGTH; ++i)
printf("%2d|: %d\n", i, wordlen);
return 0;
}
--------------- OUTPUT --------------
[arch@voodo kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-13.c
[arch@voodo kr2]$ ./a.out
like this
and
......................... about
1|: 0
2|: 0
3|: 1
4|: 2
5|: 1
6|: 0
7|: 0
8|: 0
9|: 0
10|: 0
[arch@voodo kr2]$