← Back to C Course | Chapter 2: Input & Output | Lesson 1 of 7

C printf()

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()?

c
#include <stdio.h>
int main() {
	printf("Hello from printf");
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int age = 25;
	printf("%d", age);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int a = 1, b = 2;
	printf("%d and %d", a, b);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	printf("First\n");
	printf("Second");
	return 0;
}

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

c
#include <stdio.h>
int main() {
	double price = 19.9999;
	printf("%.2f", price);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.