I tried to solve this problem, which is to count the amount of lines, blank spaces, and tabs.
My solution was incorrect because I don't know how to use { }.
main ()
{
int newline;
int tab;
int blank;
int c;
newline = 0;
tab = 0;
blank = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++newline;
if (c == '\t')
++tab;
if (c == 32)
++blank;
printf("lines: %d tabs: %d blanks: %d\n", newline, tab, blank);
}
In my code, only new lines were being counted. Tabs and spaces were never counted. I know the answer is to add { } around the if statements section. But I only know this because I searched google for the solution.
Perhaps it is just me, but K&R do not really explain when I should use { }.
Can someone explain how I can know to add { } to my above code? When I read the code, it seems fine without {}. It means I truly don't understand its usage. Why aren't tabs and spaces counted in the above code?
Is there another book on C that you can recommend? I have no programming experience.