Data Input and Output (I/O) in C refers to the process of receiving data from the user, reading data from files, and displaying data on the screen. The C language provides several built-in functions through the stdio.h library to handle standard input and output operations.
1. Standard Input and Output in C
C uses stdin (standard input) and stdout (standard output) to communicate with the user.
- Input: Getting data from the keyboard
- Output: Displaying data on the screen
The main library for this is:
#include <stdio.h>
2. Output Functions
a) printf()
Used to display formatted output.
Syntax
printf("format specifier", variables);
Example
int age = 20;
printf("Age = %d", age);
b) puts()
Used to display strings only.
puts("Hello World");
c) putchar()
Prints a single character.
putchar('A');
3. Input Functions
a) scanf()
Reads formatted input from the user.
Syntax
scanf("format specifier", &variables);
Example
int num;
scanf("%d", &num);
b) gets() (Deprecated)
Reads an entire line including spaces.
Note: Not recommended due to security issues.
gets(name);
c) fgets()
A safe alternative to gets().
fgets(name, sizeof(name), stdin);
d) getchar()
Reads a single character from user input.
char c = getchar();
4. Format Specifiers
| Data Type | Format Specifier |
|---|---|
| int | %d |
| char | %c |
| float | %f |
| double | %lf |
| string | %s |
Example:
int roll;
float marks;
scanf("%d %f", &roll, &marks);
5. Example Program for Input and Output
#include <stdio.h>
int main() {
int age;
float salary;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your salary: ");
scanf("%f", &salary);
printf("\n--- Output ---\n");
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
return 0;
}
6. Difference Between Input and Output Functions
| Function Type | Common Functions | Purpose |
|---|---|---|
| Input | scanf(), getchar(), fgets() | Read data from user |
| Output | printf(), puts(), putchar() | Display data to user |
7. Key Points
- All I/O functions belong to
stdio.h scanf()requires address operator (&) for variablesprintf()is used for formatted output- Prefer
fgets()overgets()for safety - C uses buffering, meaning input is stored temporarily before processing
🔗 View other articles about C Programming:
https://savanka.com/category/learn/c-programming/
🔗 External C Documentation:
https://www.w3schools.com/c/