Input and Output Functions in C Programming (printf and scanf)
This tutorial explains input and output operations in C programming using the printf and scanf functions. It covers syntax, format specifiers, examples, and common mistakes, helping beginners learn how to display output and accept user input effectively in C programs.
1. Introduction to Input and Output in C
Input and output operations allow a program to:
- Receive data from the user
- Display results to the user
C provides standard input and output functions through the Standard I/O library.
2. printf() Function
What is printf()?
printf() is used to display output on the screen.
Syntax
Example 1: Simple Output
Example 2: Output with Variables
Common Format Specifiers
| SpecifierData Type | |
%d | int |
%f | float |
%lf | double |
%c | char |
%s | string |
Example 3: Multiple Outputs
3. scanf() Function
What is scanf()?
scanf() is used to take input from the user.
Syntax
Note: & (address-of operator) is required for variables.
Example 1: Taking Integer Input
Example 2: Multiple Inputs
Example 3: Character Input
(The space before %c avoids reading newline characters.)
4. Complete Example Program
5. Input of Strings Using scanf
Note: scanf reads input until a space is encountered.
6. Common Mistakes to Avoid
- Forgetting
&inscanf - Using wrong format specifier
- Not handling spaces when reading characters
- Buffer overflow when reading strings
7. Difference Between printf and scanf
| Featureprintfscanf | ||
| Purpose | Output | Input |
| Direction | Program → User | User → Program |
Uses & | No | Yes |
Key Points to Remember
- Always include
<stdio.h> - Use correct format specifiers
- Use
\nfor new lines - Be careful with input buffers