THE SYLLABUS QUESTION
What you need to solve
Write a C program to count the lines, words and characters in a given text.
Text read until end-of-file (EOF). A word is a maximal sequence of non-whitespace bytes. Characters include whitespace and newline bytes. A final non-empty line without a newline is counted as a line. Use ASCII text.
UNDERSTAND THE IDEA
Explanation
Read one byte at a time with getchar. Store its result in int so EOF can be distinguished from every byte value.
Count a word only when moving from whitespace to non-whitespace. Count newline characters as line endings and add one final line if non-empty text has no terminating newline.
When typing interactively, send EOF after the text: commonly Ctrl+D on Linux/macOS, or Ctrl+Z followed by Enter on Windows. With the website compiler, use its supported input/EOF behavior; downloading and redirecting an input file is another reliable method.
PLAN BEFORE CODING
Algorithm
- Initialize counters, inWord and the last-character marker.
- Read until getchar returns EOF.
- Count every byte and every newline.
- Count a new word on each transition into non-whitespace.
- If needed, count the final unterminated line and print all totals.
SEE THE CONTROL FLOW
Flowchart
Follow the arrows from Start. Diamonds ask a question; labeled arrows show the answer. A returning arrow repeats a loop. Function internals are grouped where needed; later input checks follow the rules in the program.
On a phone, scroll sideways to read the diagram at full size. Open full-size flowchart ↗
#include <stdio.h>
#include <ctype.h>
int main(void) {
unsigned long long lines = 0, words = 0, characters = 0;
int ch, last = '\n', inWord = 0;
while ((ch = getchar()) != EOF) {
++characters;
if (ch == '\n') ++lines;
if (isspace((unsigned char)ch)) inWord = 0;
else if (!inWord) { ++words; inWord = 1; }
last = ch;
}
if (characters > 0 && last != '\n') ++lines;
printf("Lines: %llu\nWords: %llu\nCharacters: %llu\n", lines, words, characters);
return 0;
}
Code loads into the existing compiler. Enter the sample input there; sign-in and execution rules stay the same.
Compile and run locally
gcc -std=c17 text-counts.c -o lab
./labOn Windows, run .\lab.exe after compiling with GCC. The interest program requires the math library where applicable.
FOLLOW THE VALUES
Dry run
| Step / state | Operation | Result |
|---|---|---|
| Text: Hello world followed by newline | Characters | 12 including newline |
| Then C lab followed by newline | Characters | 6 more; total = 18 |
| Two newline bytes; four word starts | Lines and words | 2 lines; 4 words |
CHECK THE BEHAVIOR
Sample input & output
Each output below was produced by compiling and running this exact program. Input values are entered in the stated order; the examples do not print input prompts.
Sample 1
Hello world
C lab
Lines: 2
Words: 4
Characters: 18
Sample 2
one twoLines: 1
Words: 2
Characters: 7
Sample 3
(empty input; EOF)Lines: 0
Words: 0
Characters: 0
Common mistakes
- Count transitions into words, not the number of spaces.
- Use int for getchar and pass an unsigned-char value to isspace.
WHY THIS GROWTH RATE?
Time and space complexity
Time O(number of input bytes); auxiliary space O(1).
Let B be the number of input bytes, including spaces and newlines. getchar processes each byte once. The program updates a few counters and a word-state flag for each byte; no previous text is rescanned.
A single traversal gives O(B) time. Text is processed as a stream rather than stored in an array, so only counters and state variables are retained: O(1) auxiliary space. Counting a final line after EOF adds constant work.
Big-O describes how work grows as the stated input quantity grows; fixed factors and lower-order terms are omitted. The analysis treats fixed-width arithmetic as constant cost and the published limits as practical safety bounds.
PREPARE FOR YOUR LAB VIVA
Related viva questions & answers
Try answering aloud, then expand the answer to check your reasoning. These questions focus on the concepts used in this program.
Why is the result of getchar stored in int rather than char?
getchar returns an unsigned-character value converted to int, or the separate EOF value. An int can distinguish all possible input bytes from EOF without losing that distinction.
How does the program recognize the beginning of a word?
A non-whitespace character begins a word only when the program was previously outside a word. Consecutive non-whitespace characters remain part of that same word.
Why does the program use isspace instead of checking only for an ordinary space?
Words can also be separated by tabs, newlines and other whitespace. isspace recognizes these separators, so repeated or mixed whitespace does not create extra words.
Why is an input byte converted to unsigned char before calling isspace?
The ctype functions accept EOF or values representable as unsigned char. Converting a stored character value to unsigned char avoids passing a negative char value outside that permitted range.
Does the character count include spaces and line endings?
Yes. Every input byte read before EOF contributes to the count, including whitespace. Here characters means bytes, so a multibyte encoded symbol can contribute more than one.
How is a final line without a newline counted?
The program counts newline-terminated lines and then accounts for a nonempty final unterminated line. Thus the text hello with no newline still contains one line, while empty input contains zero.