One of the first things every C programmer learns is how to interact with users. A program that cannot receive input or display output is not very useful.
In C, this interaction is handled primarily by two standard library functions:
printf()for output
scanf()for input
Let's see how they work and why they are so important.
What is printf()?
printf() stands for Print Formatted.
It is used to display output on the screen.
#include <stdio.h>
int main()
{
printf("Hello, World!");
return 0;
}
Output:
Hello, World!
The function can also display variable values using format specifiers.
int age = 23;
printf("Age = %d", age);
Output:
Age = 23
Here, %d tells printf() to display an integer.
What is scanf()?
scanf() stands for Scan Formatted.
It reads input from the keyboard and stores it in variables.
int age;
scanf("%d", &age);
The & operator is important because scanf() needs the memory address where the value should be stored.
Complete example:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered: %d", age);
return 0;
}
Common Format Specifiers
| Specifier | Type |
|---|---|
%d | int |
%f | float |
%lf | double |
%c | char |
%s | string |
Example:
float salary = 45000.50;
char grade = 'A';
printf("%f\n", salary);
printf("%c\n", grade);
A Common Beginner Mistake
Many beginners forget the & operator.
Incorrect:
scanf("%d", age);
Typical compiler warning:
warning: format '%d' expects argument of type 'int *'
Correct:
scanf("%d", &age);
How scanf() and printf() Work Internally
A useful mental model is:
Keyboard
↓
scanf()
↓
Memory
↓
printf()
↓
Monitor
When a user enters a value:
scanf()reads the input.- The value is stored in memory.
printf()reads the value from memory.- The result is displayed on the screen.
Understanding this flow makes later topics such as pointers and memory management much easier.
Key Takeaways
printf()displays output.
scanf()accepts input.- Format specifiers determine how data is interpreted.
- The
&operator provides a memory address. - These functions are fundamental to almost every beginner C program.
SOCIAL SHARE CARD GENERATOR