CBasics

C Input and Output (printf & scanf)

Learn how to take input from users and display output in C using printf and scanf, including format specifiers and common pitfalls. đź“– C Input and Ou

What is Input and Output in C?Link to this section

Input and output (I/O) in C allow programs to interact with users.
  • Input means taking data from the user
  • Output means displaying results to the user
C uses standard input and output functions provided by the <stdio.h> header file.

The "printf" Function :Link to this section

The printf function is used to display output on the screen. It prints formatted text to the standard output (usually the console).
Syntax of printf

Simple Output Using printf :Link to this section

note

This prints the text exactly as written inside the quotes.

Printing Variables Using printf :Link to this section

To print variable values, format specifiers are used.
Explanation: %d tells C to print an integer value.

Common Format Specifiers :Link to this section

%d Used for integers %f Used for floating-point numbers %c Used for characters %s Used for strings (character arrays)

note

Using the wrong format specifier leads to incorrect output.

The "scanf" Function :Link to this section

The scanf function is used to take input from the user. It reads formatted input from standard input (keyboard).
Syntax of scanf
Explanation: The address-of operator (&) is required to store input into variables.

Taking Integer Input :Link to this section

Taking Multiple Inputs :Link to this section

Explanation: Multiple values can be read in a single scanf call.

Input and Output with float :Link to this section

note

%.2f prints the float value up to two decimal places.

Using scanf with Characters :Link to this section

note

The space before %c avoids reading leftover whitespace.

Common Mistakes in scanf :Link to this section

  • Forgetting & before variable names
  • Using wrong format specifier
  • Mixing scanf with unsafe input methods
New text block

warning

Incorrect usage of scanf can cause runtime errors or incorrect input.

Why Input/Output is Important :Link to this section

I/O allows programs to:
  • Accept user data
  • Display results dynamically
  • Build interactive applications

tip

Mastering printf and scanf is essential before moving to file handling.
Check Your Understanding
Question 1 of 5

Which header file is required for printf and scanf?

Practice Challenges

medium
  • Write a program to input and print your name and age.
  • Take two integers from the user and print their sum.
  • Input a float value and print it with three decimal places.
  • Fix errors in a program where scanf is missing &.