printf formatting
- C course
- Beginner
- Lesson 30/116
- 4 min
Learn printf format specifiers (%d, %f, %s, %c).
printf and format specifiers
The printf function prints formatted output to the screen. You place format specifiers inside the double-quoted text; each specifier is replaced by the next variable.
int age = 25;
double price = 19.99;
char grade = 'A';
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);Common specifiers: %d integer, %f floating-point, %c single character, %s string. %.2f shows two digits after the dot. The escape sequence \n moves to a new line.
Multiple specifiers
You can use several specifiers in a single printf call. The order of specifiers matches the order of the comma-separated variables.
int rows = 3;
int cols = 4;
printf("Matrix: %d x %d\n", rows, cols);Output: Matrix: 3 x 4. The first %d takes rows, the second %d takes cols. The specifier count must equal the variable count; missing or extra values cause undefined behavior.
Practice Print three variables formatted
Write a C program. Declare int age = 25;, double price = 19.99; and char grade = 'A';. Print each on its own line with printf: Age: 25, Price: 19.99, Grade: A. Add #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare the variables and print them with printf
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int age = 25;
double price = 19.99;
char grade = 'A';
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);
return 0;
}Expected output
Age: 25 Price: 19.99 Grade: A
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which type is the %d specifier for?
int n = 5;
printf("%d", n);- double
- char
- int Correct answer
- string
Explanation: %d is used for the integer (int) type.
2 Pick the decimal specifier
printf("Price: ____", price);
printf("Price: %.2f", price);
Explanation: %.2f shows two decimal digits.
3 Match the specifiers
| Term | Meaning |
|---|---|
%d |
Integer |
%.2f |
Two decimals |
%c |
Single character |
%s |
String |