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.
#include <stdio.h>
2. printf() Function
What is printf()?
printf() is used to display output on the screen.
Syntax
printf("format string", variables);
Example 1: Simple Output
printf("Welcome to C Programming");
Example 2: Output with Variables
int age = 25;
printf("Age is %d", age);
Common Format Specifiers
| SpecifierData Type | |
%d | int |
%f | float |
%lf | double |
%c | char |
%s | string |
Example 3: Multiple Outputs
int id = 101;
float salary = 45000.75;
printf("ID: %d\nSalary: %.2f", id, salary);
3. scanf() Function
What is scanf()?
scanf() is used to take input from the user.
Syntax
scanf("format string", &variable);
Note: & (address-of operator) is required for variables.
Example 1: Taking Integer Input
int number;
scanf("%d", &number);
Example 2: Multiple Inputs
int age;
float salary;
scanf("%d %f", &age, &salary);
Example 3: Character Input
char grade;
scanf(" %c", &grade);
(The space before %c avoids reading newline characters.)
4. Complete Example Program
#include <stdio.h>
int main() {
int age;
float salary;
char grade;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter salary: ");
scanf("%f", &salary);
printf("Enter grade: ");
scanf(" %c", &grade);
printf("\nDetails Entered:\n");
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
printf("Grade: %c\n", grade);
return 0;
}
5. Input of Strings Using scanf
char name[20];
scanf("%s", name);
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