Section 1.5.3 Line Counting#
Program#
#include <stdio.h>
/* count lines in input */
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
Explanation#
This Program counts input lines. The program does that counting by setting a variable nl to 0 in the beginning. As the program one character at a time in the while loop ((c = getchar()) != EOF) till the EOF. If the character is newline character ānā the number of lines variable is incremented, ++nl. At the end, the number of lines, nl, is printed.
See also
This document was updated on 20 May of 22