C-Program
printf() and scanf() method in C
Last Updated on: 3rd Jul 2025 15:07:23 PM
In C programming, we use printf()
to display output on the screen and scanf()
to take input from the user.
These functions are part of the stdio.h
(Standard Input Output) library, so you must include this header at the top of your program.
#include <stdio.h>
printf()
– Output Function
The printf()
function is used to print or display text, variables, or results to the screen.
Syntax:
printf("format string", variables);
Example:
#include <stdio.h>
int main() {
int age = 20;
printf("My age is %d", age);
return 0;
}
Output:
My age is 20
Common Format Specifiers for printf()
| Specifier | Meaning | Example |
| --------- | --------------------------- | -------------------------- |
| `%d` | Integer | `printf("%d", 10);` |
| `%f` | Float | `printf("%f", 3.14);` |
| `%.2f` | Float with 2 decimal places | `printf("%.2f", 3.14159);` |
| `%c` | Character | `printf("%c", 'A');` |
| `%s` | String | `printf("%s", "Hello");` |
scanf()
– Input Function
The scanf()
function is used to accept input from the user during program execution.
Syntax:
scanf("format string", &variable);
Note: We use the
&
(address-of) operator to store the user input in the variable.
Example:
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered: %d", age);
return 0;
}
Sample Input/Output:
Enter your age: 25
You entered: 25
Common Format Specifiers for scanf()
| Specifier | Meaning |
| --------- | ------------------ |
| `%d` | Integer |
| `%f` | Float |
| `%c` | Character |
| `%s` | String (no spaces) |
NOTE : To accept strings with spaces, use fgets()
instead of scanf()
.
Multiple Input Example :
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d", a + b);
return 0;
}
Sample Input/Output:
Enter two numbers: 4 5
Sum = 9
-
printf() is for output, scanf() is for input.
-
Always use
&
before variable names inscanf()
(except for strings). -
Both functions are part of the
<stdio.h>
library. -
scanf() cannot read spaces in strings — for that, use fgets().