DEV Community

Moksh Upadhyay
Moksh Upadhyay

Posted on • Originally published at mokshelearning.blogspot.com

printf() and scanf() in C: Understanding Input and Output

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;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, World!
Enter fullscreen mode Exit fullscreen mode

The function can also display variable values using format specifiers.

int age = 23;

printf("Age = %d", age);
Enter fullscreen mode Exit fullscreen mode

Output:

Age = 23
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

A Common Beginner Mistake

Many beginners forget the & operator.

Incorrect:

scanf("%d", age);
Enter fullscreen mode Exit fullscreen mode

Typical compiler warning:

warning: format '%d' expects argument of type 'int *'
Enter fullscreen mode Exit fullscreen mode

Correct:

scanf("%d", &age);
Enter fullscreen mode Exit fullscreen mode

How scanf() and printf() Work Internally

A useful mental model is:

Keyboard
   ↓
scanf()
   ↓
Memory
   ↓
printf()
   ↓
Monitor
Enter fullscreen mode Exit fullscreen mode

When a user enters a value:

  1. scanf() reads the input.
  2. The value is stored in memory.
  3. printf() reads the value from memory.
  4. 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.

Top comments (0)