Saitama
Saitama

Reputation: 11

K&R Section 1.5.3 Line Counting

i just answered a question from K&R Which was "Write a program that counts blanks , tabs, and newlines"

And Heres my code

#include <stdio.h>
#include <stdlib.h>

main()
{
 /* Program  counts Number of lines, Spaces, and Tabs from user input*/

 int c, nl,tabs,spaces;
 spaces = 0;
 tabs = 0;
 nl = 0;

 while ((c = getchar()) != EOF)
          if(c =='\t')
                 ++tabs;
                  else if(c==' ')
                       ++spaces;
                        else if (c == '\n')
                                 ++nl;

 printf("Newlines %d\nTabs %d\nSpaces %d", nl, tabs, spaces);
return 0;
}

The Output runs exactly the same.. but the book got a different answer. So am i Incorrect?

Upvotes: 1

Views: 244

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148870

As you declared yourself a learned, I will just add some remarks.

You should always declare main as int main(...). In early (K&R) times, every function that did not have a proper declaration was assumed to return int, but it is deprecated in modern versions.

while ((c = getchar()) != EOF) is correct as c is declared as int. But your indentation is misleading: it is better to write else if or else at same level as the original if.

Last (even if it is rather a matter of taste), you did not put curly brackets around any of the blocs. It is correct because there is one single statement after each if, and in that case, the full if ... else ... counts for a single instruction. But this would be a nightmare for future maintainers in a real world program. My advice is to always write curly braces if you indent, and only omit them when the instruction is written on same line as the if.

Upvotes: 1

Related Questions