📖 Basic Input and Output in C
🎭 The Messenger Analogy
Imagine your computer program is like a messenger service. Sometimes you need to send messages OUT (show things on screen), and sometimes you need to receive messages IN (get information from the user). That’s exactly what Input and Output (I/O) does in C!
🖨️ The printf Function — Your Program’s Voice
Think of printf as your program’s mouth. When your program wants to say something to the world, it uses printf.
What is printf?
printf means “print formatted” — it prints text to the screen in a format you choose.
Simple Example
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
Output: Hello, World!
That’s it! Your program just spoke its first words! 🎉
How printf Works
graph TD A[Your Message] --> B[printf function] B --> C[Screen/Terminal] C --> D[👀 User sees it!]
📥 The scanf Function — Your Program’s Ears
If printf is the mouth, then scanf is the ears. It listens to what the user types.
What is scanf?
scanf means “scan formatted” — it reads input from the user in a format you specify.
Simple Example
#include <stdio.h>
int main() {
int age;
printf("How old are you? ");
scanf("%d", &age);
printf("You are %d years old!", age);
return 0;
}
What happens:
- Program asks: “How old are you?”
- User types:
10 - Program says: “You are 10 years old!”
🔑 The Magic Ampersand (&)
See that & before age? It means “the address of”. It tells scanf WHERE to store the answer. Like giving someone your home address so they can deliver a package!
graph TD A[User types on keyboard] --> B[scanf listens] B --> C["& tells WHERE to store"] C --> D[Variable holds the value]
🏷️ Format Specifiers — The Secret Codes
Format specifiers are like secret codes that tell printf and scanf what TYPE of data you’re dealing with.
The Most Common Codes
| Code | Meaning | Example |
|---|---|---|
%d |
Integer (whole number) | 42, -5, 100 |
%f |
Float (decimal number) | 3.14, -2.5 |
%c |
Character (single letter) | ‘A’, ‘z’, ‘7’ |
%s |
String (word/sentence) | “Hello” |
%lf |
Double (big decimal) | 3.14159265359 |
Using Format Specifiers
int score = 95;
float price = 19.99;
char grade = 'A';
printf("Score: %d\n", score);
printf("Price: %f\n", price);
printf("Grade: %c\n", grade);
Output:
Score: 95
Price: 19.990000
Grade: A
🎯 Memory Trick
- %d = digits (whole numbers)
- %f = floating point (decimals)
- %c = character (one letter)
- %s = string (text)
📏 Field Width and Precision — Making Things Pretty
Want your output to look neat and organized? Field width and precision are your tools!
Field Width
Field width sets the minimum space for your output. Like reserving seats at a table!
printf("%5d\n", 42); // Right-aligned
printf("%-5d\n", 42); // Left-aligned
Output:
42
42
The number 5 means “use at least 5 spaces.”
Precision (for decimals)
Precision controls how many digits appear after the decimal point.
float pi = 3.14159;
printf("%.2f\n", pi); // 2 decimal places
printf("%.4f\n", pi); // 4 decimal places
Output:
3.14
3.1416
Combining Both
printf("%8.2f\n", 3.14159);
This means: 8 total spaces, 2 after decimal = 3.14
graph LR A["%8.2f"] --> B["8 = total width"] A --> C[".2 = decimal places"] A --> D["f = float type"]
🚪 Escape Sequences — The Invisible Commands
Some characters are invisible but powerful! They’re called escape sequences because they “escape” from being normal text.
The Escape Family
| Sequence | What It Does | Think of it as… |
|---|---|---|
\n |
New line | Pressing Enter |
\t |
Tab space | Pressing Tab |
\\ |
Backslash | The \ itself |
\" |
Double quote | The " mark |
\' |
Single quote | The ’ mark |
\0 |
Null character | “The End” signal |
Examples in Action
printf("Hello\nWorld");
// Output:
// Hello
// World
printf("Name:\tJohn");
// Output: Name: John
printf("She said \"Hi!\"");
// Output: She said "Hi!"
💡 Why the Backslash?
The backslash \ is like a magic wand that transforms the next character into something special!
✍️ getchar and putchar — One Letter at a Time
Sometimes you just want to handle one character. That’s where getchar and putchar come in!
getchar — Get One Character
char letter;
printf("Type a letter: ");
letter = getchar();
printf("You typed: ");
putchar(letter);
What happens:
- User types:
A - getchar grabs just that one ‘A’
- putchar displays it back
putchar — Put One Character
putchar is simpler than printf — it just puts ONE character on screen.
putchar('H');
putchar('i');
putchar('!');
// Output: Hi!
When to Use Them?
graph TD A{What do you need?} A -->|One character| B[getchar/putchar] A -->|Multiple items| C[scanf/printf] B --> D[Simpler & Faster] C --> E[More Flexible]
🌊 stdin, stdout, stderr — The Three Streams
Think of your program as a kitchen with three different pipes:
The Three Pipes
| Stream | Full Name | What It Does | Kitchen Analogy |
|---|---|---|---|
stdin |
Standard Input | Where input comes from | Water tap (stuff comes IN) |
stdout |
Standard Output | Where normal output goes | Drain (stuff goes OUT) |
stderr |
Standard Error | Where errors go | Garbage disposal (problems go here) |
How printf Uses stdout
printf("Hello!"); // Goes to stdout
// Same as:
fprintf(stdout, "Hello!");
How scanf Uses stdin
int x;
scanf("%d", &x); // Reads from stdin
// Same as:
fscanf(stdin, "%d", &x);
stderr for Errors
fprintf(stderr, "Error: File not found!");
Why separate error messages? So you can redirect normal output somewhere else while still seeing errors!
Visual Flow
graph LR A[Keyboard] -->|stdin| B[Your Program] B -->|stdout| C[Screen - normal text] B -->|stderr| D[Screen - error messages]
🎮 Putting It All Together
Here’s a complete example using everything we learned:
#include <stdio.h>
int main() {
char name[50];
int age;
float height;
printf("=== Welcome! ===\n\n");
printf("What's your name? ");
scanf("%s", name);
printf("How old are you? ");
scanf("%d", &age);
printf("How tall (meters)? ");
scanf("%f", &height);
printf("\n--- Your Info ---\n");
printf("Name:\t%s\n", name);
printf("Age:\t%d years\n", age);
printf("Height:\t%.2f m\n", height);
return 0;
}
Sample Run:
=== Welcome! ===
What's your name? Alex
How old are you? 10
How tall (meters)? 1.35
--- Your Info ---
Name: Alex
Age: 10 years
Height: 1.35 m
🌟 Key Takeaways
- printf = program speaks (output)
- scanf = program listens (input)
- Format specifiers = %d, %f, %c, %s tell what type of data
- Field width = how much space to use
- Precision = decimal places for floats
- Escape sequences = invisible commands like \n and \t
- getchar/putchar = one character at a time
- stdin/stdout/stderr = the three data streams
🚀 You Did It!
You now understand how C programs talk to the world and listen to users! This is the foundation of every interactive program.
Remember: printf is the mouth, scanf is the ears, and format specifiers are the language they speak! 🎤👂