C printf()
In this page:
What is printf()?
printf ("print formatted") is the standard C library function for writing text and variable values to the screen -- it's part of stdio.h and is the primary way a C program communicates anything back to the person running it.
Example: What is printf()?
#include <stdio.h>
int main() {
printf("Hello from printf");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Variables
Format specifiers like %d or %s inside a printf string act as placeholders that get replaced, in order, by the values of the arguments you pass after the format string -- mismatching the specifier and the variable's type produces garbage output.
Example: Printing Variables
#include <stdio.h>
int main() {
int age = 25;
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Multiple Values
When printf is called with multiple format specifiers, each one consumes the next argument in the list in left-to-right order, so printf("%d and %d", a, b) prints a's value first and b's second, matching their position.
Example: Printing Multiple Values
#include <stdio.h>
int main() {
int a = 1, b = 2;
printf("%d and %d", a, b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Newlines in Output
Because printf never adds a line break on its own, consecutive printf calls print immediately next to each other on the same line unless you explicitly include \n wherever you want output to move to a new line.
Example: Using Newlines in Output
#include <stdio.h>
int main() {
printf("First\n");
printf("Second");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Formatting Floating-Point Precision
Writing %.2f instead of %f rounds a floating-point value to exactly 2 decimal places when printed -- essential for displaying things like currency cleanly instead of C's default of six digits after the decimal point.
Example: Formatting Floating-Point Precision
#include <stdio.h>
int main() {
double price = 19.9999;
printf("%.2f", price);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: