Input & Output in C
Input & Output in C
Introduction
In any programming language, interacting with the user is very important.
This is done using Input and Output operations.
- Output → Displaying data to the user
- Input → Taking data from the user
In C, we mainly use:
-
printf()→ for output -
scanf()→ for input
Header File Required
To use input and output functions, include:
#include <stdio.h>
printf() Function
printf() is used to display output on the screen.
Syntax
printf("message");
Example
#include <stdio.h>
int main() {
printf("Welcome to Dharani Tech Edu Hub!");
return 0;
}
Output
Welcome to Dharani Tech Edu Hub!
Using Variables with printf()
#include <stdio.h>
int main() {
int age = 20;
printf("Age = %d", age);
return 0;
}
Output
Age = 20
Format Specifiers
Used to display different data types:
| Data Type | Format Specifier |
|---|---|
| int | %d |
| float | %f |
| char | %c |
| double | %lf |
scanf() Function (Input)
scanf() is used to take input from the user.
Syntax
scanf("format_specifier", &variable);
👉 & is called address-of operator
Example
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered: %d", age);
return 0;
}
Sample Output
Enter your age: 18
You entered: 18
Multiple Inputs
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d", a + b);
return 0;
}
Output
Enter two numbers: 5 10
Sum = 15
Important Notes
-
✔ Always use
&before variable inscanf() - ✔ Match format specifier with data type
-
✔ Use
\nfor new line
🔹 Common Mistakes
-
❌ Forgetting
&inscanf() - ❌ Wrong format specifier
-
❌ Missing
#include <stdio.h> - ❌ Not initializing variables properly
Pro Tips
-
✔ Use clear prompts (
Enter value:) - ✔ Validate user input (advanced level)
- ✔ Practice input/output programs daily
- ✔ Combine multiple inputs and outputs
Difference Between printf() and scanf()
Difference Between printf() and scanf()
This table explains the key differences between printf() and scanf() functions in C programming.
| Feature | printf() | scanf() |
|---|---|---|
| Purpose | Output | Input |
| Usage | Displays data | Takes user input |
| Symbol | No & needed | & required |
Conclusion
Input and Output functions are the basic building blocks of any C program. They allow interaction between the user and the program.
Mastering printf() and scanf() is essential before moving to advanced topics.
Comments
Post a Comment