next up previous
Next: Line Counting Up: Character Input and Output Previous: File Copying

Character Counting

#include <stdio.h>

/* count characters in input; 1st version */
main()
{
  long nc;

  nc = 0;
  while (getchar() != EOF)
    ++nc;
  printf("%ld\n", nc);
}
$\bullet$
Concepts: Increment operator; long types
$\bullet$
Increment (++) and decrement (-) operators can be prefix or postfix
#include <stdio.h>

/* count characters in input; 2nd version */
main()
{
  double nc;

  for (nc = 0; getchar() != EOF; ++nc)
    ;
  printf("%.0f\n", nc);
}
$\bullet$
Concepts: Null statement


Derek C. Richardson 2005-02-03