Learn C
#include "ioformatting/char_io.h"

Character I/O: getchar & putchar in C

#concept

getchar() reads one character (as int, to represent every char plus EOF) and putchar(c) writes one — the simplest possible I/O pair, and the engine of K&R-style text filters. The int return type is load-bearing: char cannot hold EOF distinctly from 0xFF on some platforms, so int c; while ((c = getchar()) != EOF) is the correct loop shape.

Character I/O looks trivial but teaches buffering truthfully: terminals deliver whole lines (canonical mode), files deliver bytes. Filters compose (prog1 | prog2) precisely because these primitives speak raw streams.

#how it works
1

int, not char, for input

int c = getchar(); — EOF (-1) must be distinguishable from every byte value, which char cannot guarantee.

2

The copy loop

while ((c = getchar()) != EOF) putchar(c); copies stdin to stdout byte-perfectly — the filter archetype.

3

Count and transform

Increment counters, map cases, collapse whitespace inside the loop — wc, tr, and grep all start here.

4

Terminals buffer lines

Interactive input arrives per-line (until Enter); files and pipes stream continuously — same code, different pacing.

#example
#include <stdio.h>
 
int main(void) {
int c;
long n = 0;
while ((c = getchar()) != EOF) {
if (c == '\n')
++n;
}
printf("%ld\n", n);
return 0;
}
Output
3
1c is int so EOF compares correctly; n counts newlines as a long.
2Each getchar() result is tested before use — comparison against '\n' needs the quotes to mean newline, not letter-n.
3Three input lines yield three newlines, so 3 prints at EOF.
#use cases
wc-style counters (lines, words, characters) in a dozen lines
Case conversion and whitespace filters with putchar
Pipelines: small stdin-to-stdout tools composing via shell pipes
Always declaring the input holder int to keep EOF distinct

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.