Skip to content

Module 2 · Variables, Types, Input and Operators — topic 4 of 6

Input and Output

printf formats output with conversion specifiers, widths and precision; scanf reads typed values into variables through their addresses. Learn both, and how to read input safely.

Beginner 16 min read·Lesson 8 of 37 in C Programming

Learning objectives

  • Use printf conversion specifiers, field widths and precision
  • Read numbers, characters and words with scanf
  • Check scanf's return value and avoid common input bugs

Definition

Formatted I/O in C is provided by <stdio.h>: printf converts values to text according to a format string and writes them to standard output, and scanf reads text from standard input, converts it according to a format string, and stores the results through pointer arguments.

Introduction

Interactive programs need to talk to the user. In C, printf does the talking and scanf does the listening. Both are driven by a format string full of % conversion specifiers that say what type each value is.

Input is where many beginner C programs break: a missing &, a stray newline left in the input buffer, or a user typing letters where a number is expected. This lesson covers the rules that avoid those problems.

Why it matters

Correctly formatted output — aligned columns, fixed decimals — is expected in every lab assignment and in real reports.

Robust input handling separates programs that work in a demo from programs that survive real users.

Detailed explanation

SpecifierTypeExample output
%d / %iint42
%uunsigned int42
%ld, %lldlong, long long9000000000
%fdouble (printf)3.140000
%.2fdouble, 2 decimals3.14
%edouble, scientific3.140000e+00
%ccharA
%sstring (char *)hello
%xunsigned, hex2a
%ppointer0x7ffc…
%%a literal %%

A field width pads output: %5d right-aligns in 5 columns, %-5d left-aligns. Precision after a dot sets decimal places for %f (%.3f) or maximum characters for %s (%.3s).

scanf needs the address of each variable so it can store into it: scanf("%d", &age);. Arrays such as char name[20] already decay to an address, so no & is used with %s.

In scanf, %f reads a float and %lf reads a double (in printf, %f works for both). %s reads one whitespace-delimited word; give it a width (%19s) to avoid overflowing the array.

scanf returns the number of items successfully converted. Checking it is the simplest way to detect bad input. Most specifiers skip leading whitespace, but %c does not — write " %c" with a leading space to skip a leftover newline.

Syntax

C
printf("format", value1, value2, ...);
int ok = scanf("format", &var1, &var2, ...);
printf("%-10s|%6.2f|\n", name, price);
scanf("%d %lf", &qty, &price);
scanf(" %c", &choice); /* leading space skips whitespace */
scanf("%19s", name); /* width protects a char[20] */
  • The number and types of arguments must match the specifiers exactly.
  • & gives the address of a variable; it is required in scanf but not in printf.
  • scanf returns how many values it stored, or EOF at end of input.

Code examples

Formatting output

C
#include <stdio.h>
int main(void) {
double price = 49.5;
int qty = 3;
printf("[%5d]\n", qty);
printf("[%-5d]\n", qty);
printf("[%.2f]\n", price);
printf("[%8.1f]\n", price * qty);
printf("Discount: 10%%\n");
return 0;
}
Output
[    3]
[3    ]
[49.50]
[   148.5]
Discount: 10%

Reading two numbers

C
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("\nSum = %d\n", a + b);
return 0;
}
Input
12 30
Output
Enter two integers: 
Sum = 42

The user's typing is not part of the program's output; the sample input is shown separately.

More examples

Validating input with the return value

C
#include <stdio.h>
int main(void) {
int age;
char grade;
printf("Age: ");
if (scanf("%d", &age) != 1) {
printf("\nThat was not a number.\n");
return 1;
}
printf("\nGrade (A-F): ");
scanf(" %c", &grade); /* space skips the newline after the age */
printf("\nAge %d, grade %c\n", age, grade);
return 0;
}
Input
19
B
Output
Age: 
Grade (A-F): 
Age 19, grade B

Step-by-step explanation

  • scanf("%d", &age) returns 1 when it stores an integer; anything else means the input was not a number, so the program stops with status 1.
  • After reading 19, the newline the user pressed is still waiting in the input buffer.
  • " %c" — note the space — skips that newline and any spaces before reading the grade character.
  • Without the space, %c would read the newline itself and grade would not be 'B'.

Expected output

Running “Validating input with the return value” with the sample input shown prints exactly:

TextInput
19
B
TextOutput
Age:
Grade (A-F):
Age 19, grade B

Practical applications

  • Command-line tools print aligned tables with width specifiers.
  • Log files use fixed formats such as %04d-%02d-%02d for dates.
  • Competitive programming judges feed input through standard input exactly as in these examples.

Best practices

  • Always check what scanf returns.
  • Give every %s a width one less than the array size.
  • Prompt the user clearly and print a newline at the end of every output line.

Common mistakes

Forgetting & in scanf

Avoid

int n;
scanf("%d", n);

Prefer

int n;
scanf("%d", &n);

scanf receives the value of n instead of its address and writes to a random location — undefined behaviour, often a crash.

Using %f to read a double

Avoid

double d;
scanf("%f", &d);

Prefer

double d;
scanf("%lf", &d);

%f tells scanf it has a float *; writing 4 bytes into an 8-byte double produces nonsense.

Using gets()

Avoid

char name[20];
gets(name);

Prefer

char name[20];
fgets(name, sizeof name, stdin);

gets cannot limit input length and was removed from C11. fgets stops at the buffer size.

Important notes

  • Standard output is usually line-buffered: text without a trailing \n may appear late. fflush(stdout) forces it out.
  • fflush(stdin) is undefined behaviour in standard C; skip leftover characters by reading them instead.

Key takeaways

  • printf formats values; specifiers must match argument types.
  • scanf needs addresses (&var) and returns how many items it read.
  • %lf reads a double; " %c" skips whitespace before a character.

Try it yourself

  1. 1
    Read a student's name (one word) and three marks, and print the name and average to two decimals.
    Show hint

    Use %19s for the name and %d three times.

  2. 2
    Print a 3-row table of item, quantity and price with aligned columns using field widths.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is wrong with `scanf("%d", n);` where n is an int?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic