Hello,

I'm attempting to learn C through the K&R book and am having some trouble with Exercise 1-13 at the moment. I'm just attempting to do a simple horizontal graph and can't figure out why this isn't working correctly. It seems to be ignoring my first "if" statement and just counting spaces/new lines/tabs into the current array index. It never increases the index.

Any thoughts? Thanks for your help!

#include <stdio.h>

main()
{
	int c, i, j, k;
	int lword[20];
	
	j = 0;

	for(i = 0; i <= 20; ++i)
		lword[i] = 0;

	while((c = getchar()) != EOF) {
		if(c != ' ' || c != '\t' || c != '\n')
			++lword[j];
		else
			++j;
	}

	for(i = 0; i <= 20; ++i) {
		printf("lword[%d] = ", i);
		for(k=0; k <= lword[i]; ++k)
			putchar('|');
		printf("\n");
	}
}

Here's the typical result:

C:\Program Files\Microsoft Visual Studio 10.0\VC>hellow
This is a test. One Two Three.
^Z
lword[0] = ||||||||||||||||||||||||||||||||
lword[1] = |
lword[2] = |
lword[3] = |
lword[4] = |
lword[5] = |
lword[6] = |
lword[7] = |
lword[8] = |
lword[9] = |
lword[10] = |
lword[11] = |
lword[12] = |
lword[13] = |
lword[14] = |
lword[15] = |
lword[16] = |
lword[17] = |
lword[18] = |
lword[19] = |
lword[20] = |

C:\Program Files\Microsoft Visual Studio 10.0\VC>

Your IF statement is always true. Write a truth table and see why.

How about a small description of the problem for the people who do not have the K & R text book ????

From the code you have written I guess you are trying to count the number of spaces / tabs / new line characters in a sentence ?
If yes then you have to store all the spaces at 1 particular index in the array lword . Similarly all the tabs have to be stored at 1 particular index

Ahh, thanks WaltP. It's funny how you miss these things when you've been staring at the problem for hours...

abhiminapal - Sorry, bad assumption on my part that folks here were familiar with it :)

The problem is: Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

I'll work on this some more and probably be back with more questions! Thanks for your help everyone.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.