printf: Printing Values
Print numbers, decimals and characters with printf and format codes like %d, %.2f and %c.
C · beginner · 6 min · 8 steps · free
What you'll learn
- Use %d, %f, %c and %s
- Control decimals and width
- End lines with \n
printf_basics.c
#include <stdio.h>
int main(void) {
int age = 21;
double price = 4.5;
char grade = 'A';
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c, padded: [%5d]\n", grade, age);
return 0;
}
Step by step
age is an int: a whole number, stored on the stack.price is created on the stack with the value 4.5.- A char holds one character, written in single quotes.
- %d is replaced by the int
age. \n moves to a new line. - %.2f prints a double with exactly two decimals: 4.50.
- %c prints a char; %5d pads the number to 5 characters wide.
- The method returns
0. - Three lines printed. Each % code took the next value in order and formatted it by its type.
Common mistakes
- Using %d for a double, which prints garbage
Best practices
- Match every format code to the type of its value
Key takeaways
- printf fills % codes with values, in order.
- %d int, %f double, %c char, %s text.
- %.2f sets decimals; %5d sets a minimum width.
Check yourself
Which code prints a char?
Answer: %c. c for character.
printf("%d", 7.5) is?
Answer: A bug: %d expects an int. The format must match the type.
Data Types and sizeof →
More in C Basics