NBC 103 • Unit 114 min readHigh Exam Frequency

Formatted & Unformatted Input/Output (I/O) Operations

Unit 1: Algorithms, Flowcharts & C Program ArchitectureProblem Solving Using C

👨‍🏫 Professor's Mental Model: The Stencil Printing Press vs Raw Unsorted Mail Stream

Formatted I/O (printf, scanf) ek customized printing stencil jaisa hai: aap specify karte ho ki number kitne decimal places me dikhega (%0.2f), ya text kitne blocks me right-align hoga (%10s). Jabki Unformatted I/O (getchar, putchar, gets, puts) ek simple conveyor belt jaisa hai jo bina kisi formatting ya translation ke raw characters ko ek-ek karke seedha andar ya bahar bhejta hai!

Academic Lecture Notes & Solved Study Pages

Unit 1 • Core Concepts, Step-by-Step Proofs & Notebook Solutions

4 Notebook Pages
NOTEBOOK PAGE 1 OF 4

1. The 3 Standard I/O Streams in C

Every executing C program is automatically connected to 3 standard text streams via `<stdio.h>`:

stdin (Standard Input): Default input stream attached to the keyboard.
stdout (Standard Output): Default output stream directed to the terminal screen (buffered).
stderr (Standard Error): Unbuffered diagnostic error stream directly mapped to the console for critical error reporting.
NOTEBOOK PAGE 2 OF 4

2. Formatted Output with printf() & Field Width Modifiers

General Syntax: `printf("format string", arg1, arg2, ...);` Format Specifier Structure: `%[flags][width][.precision][length]specifier`

Flags:
- `-` : Left-justify output within the specified field width (default is right-justified).
- `+` : Explicitly print sign (+ or -) for numerical values.
- `0` : Pad field with leading zeroes instead of spaces (e.g. `%05d` for 42 prints `00042`).
Width: Minimum number of character spaces allocated (e.g., `%8d`).
Precision (`.p`):
- For floats: Number of digits after decimal point (e.g., `%.2f` for 3.14159 prints `3.14`).
- For strings: Maximum number of characters printed from string (e.g., `%.3s` for "Computer" prints "Com").
NOTEBOOK PAGE 3 OF 4

3. Formatted Input with scanf() & The Address-of (&) Operator

General Syntax: `scanf("format string", &var1, &var2, ...);`

Why is the Address-of (&) operator mandatory in scanf()? In C, function arguments are passed by value. To allow scanf() to write incoming keyboard data directly into your variable's memory cell in RAM, you MUST supply the variable's physical memory address (`&variable`).

Exception for Strings: Array names (like `char name[50]`) decay into a pointer representing their base address (`&name[0]`), so writing `&` is unnecessary: `scanf("%s", name);`.

Limitation: `scanf("%s", str)` terminates input at the first encountered whitespace (space, tab, newline). It cannot read multi-word strings like "New Delhi"!

NOTEBOOK PAGE 4 OF 4

4. Unformatted Character & String I/O Functions

Character I/O:
- `getchar()`: Reads a single character from stdin (waits for Enter key press).
- `putchar(ch)`: Writes a single character to stdout.
- `getch()` / `getche()` (from `<conio.h>`): Reads a character immediately without waiting for Enter. `getche()` echoes the character to screen; `getch()` does not.
String I/O:
- `gets(str)`: Reads an entire line including spaces until newline. CRITICAL WARNING: `gets()` is dangerous and deprecated in C99 / removed in C11 because it causes buffer overflow security vulnerabilities!
- `fgets(str, size, stdin)`: The safe standard alternative that limits the maximum characters read.
- `puts(str)`: Prints string to screen and automatically appends a newline (`\n`).
Comparison: Formatted I/O vs Unformatted I/O
ParameterFormatted I/O (printf / scanf)Unformatted I/O (getchar / fgets / puts)
Data Types SupportedAll primitive data types (int, float, char, double, string)Only individual characters and character strings
Control Over LayoutHigh - controls field width, precision, padding, decimal placesNone - outputs raw characters without formatting
Speed & OverheadSlower due to format string parsing and binary conversionFaster - performs direct byte transfers
Header FileMandatory <stdio.h><stdio.h> (and <conio.h> for getch)
Space Handlingscanf("%s") stops at first space; scanf("%[^ ]") reads linefgets() reads spaces until newline or buffer size limit

Interactive Tested Code Example

#include <stdio.h>

int main(void) {
    int item_id = 101;
    char item_name[] = "Scientific Calculator";
    float price = 850.50f;
    int quantity = 2;
    float total = price * quantity;

    printf("================================================\n");
    printf("               TAX INVOICE RECEIPT              \n");
    printf("================================================\n");
    printf("%-10s %-25s %5s %10s\n", "ITEM ID", "DESCRIPTION", "QTY", "TOTAL (RS)");
    printf("------------------------------------------------\n");
    printf("%-10d %-25s %5d %10.2f\n", item_id, item_name, quantity, total);
    printf("================================================\n");
    printf("Leading Zero Formatting Demo: Invoice #%06d\n", item_id);
    return 0;
}
💡 Note:Demonstrates advanced printf formatting flags: %-10s (left-justified field width 10), %10.2f (right-justified with 2 decimals), and %06d (6-digit zero-padded number).

🎯 University Exam Scoring Blueprint

  • In exam questions, always point out why gets() is deprecated and demonstrate the safe fgets(buffer, sizeof(buffer), stdin) alternative.
  • Explain the format string structure: %[flags][width][.precision]type.
  • Remember to state that fflush(stdin) is used to clear residual newline characters from the input buffer before reading characters.

Top Viva Questions on Formatted & Unformatted Input/Output (I/O) Operations

2 Questions
1

Why should we never use gets() in production C code?

2

What does the return value of scanf() represent?